dimanche 27 mars 2022

How to use socket gateway on NestJS services/controllers?

I'm working on a NestJS monolith application, in the near future, we'll break it into microsservices, but right now everything is on the same project.

I have a few REST APIs for database crud operations, and right now, I'm working on a new feature that is going to receive a payload from the frontend trough a websocket connection, and will then call a few methods on a specific server.

Right now, I'm a completely newbie on sockets and a beginner on Nest, so this might be an obvious and dumb question

I'm following Nest's documentation: https://docs.nestjs.com/websockets/gateways, but I'm not sure how to apply some of that on a real life application. My socket.gateway.ts has a handleConnection and a sendMessage method, but I need some advice for listening to new events. Right now, the only way I can receive messages is using @SubscribeMessage on a method inside my .gateway.ts class. But that way, my gateway must inject every service that needs to receive a socket connection payload, so I would need a new method inside my gateway for every "action", like I would if I used REST endpoints on a controller.

So, here's my questions:

  1. Following best practices, how should I receive events payload inside my other services? Should I treat the gateway as if it was "kind-of" a controller? Like a method for every "endpoint" (event) I need to receive payload on?
  2. In case question one is correct, should I have a new gateway for every service (like 1 gateway for UserService, another for AppService, and another for MessageService, just like a controller)?
  3. Also, as an extra question... My backend URL is https://example.com/service-name/example, that address is not callable trough my frontend... It tries to reach example.com, not the full URL, what am I missing?

ALSO: I'm not stuck to Nest socket.io lib, I could use another one, but I do prefer to keep using Nest's native lib as it's not my decision only, so...

Edit: I realized my question about "different services" might actually be better interpreted as "different domains".

Aucun commentaire:

Enregistrer un commentaire