Nestjs how to use http request and Websocket at the same time

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.

Answers 1

  • 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.


Related Articles