2

I have a controller in Nestjs that handles an HTTP request. There is an IoT device that communicates with the server and sends the latest changes to the server with a post request. At the same time, there is a mobile application that should receive the update in realtime with Websockets.

I know that the HTTP request and Websockets are different concepts in Nestjs, but is there any way to emit an event whenever I receive the HTTP request?

Any idea would be highly appreciated.

Vahid Najafi
  • 4,654
  • 11
  • 43
  • 88

1 Answers1

6

There is indeed a proper solution for this. You need an Injectable that contains an RxJS Subject. Whenever your Controller receives a value via the POST request, it delegates the value to the injected service. The service then "instructs" the Subject to emit the value. On the other side of the chain, inside your WebSocket Gateway @SubscribeMessage, you return an RxJS Observable - which is derived from the Subject - to the connected clients.

More on Subject and Asynchronous responses

Here is the implementation.

Vahid Najafi
  • 4,654
  • 11
  • 43
  • 88
  • maybe i don't understand well, but this approach, while great for many aspects i'm sure, doesn't allow to fully perform websocket handling when receiving an https request, or does it ? Like having a socket client join or leave a room when an http request is made, or emit events with the broadcasting method from socket.io ? Or did i miss something ? I mean, doing so would require to identify the socket client on an http request, and that is not handled by the rxjs subjects, right ? – hugogogo Jan 10 '23 at 13:24