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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 ?
I am new and I haven't heard about RxJS before. Why do we need it here?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.