Implement request-response socket.io-client to nestjs microservice
In the last story, I introduced how to implement socket.io-client to nestjs microservice. But it was used just as pub-sub system that client can only publish and subscribe to message. Sometime we need to send message to server and wait the response like a http request. This story will introduce how do I do it.
First, the ideal I used is before I emit a message to server, I give an ID to this message. And when server receive message, it can handle and emit new message to client with same ID with message it receive.

So to do that, first I add new provider named: request-store.provider.ts
Then I edit my ClientProxy.
As you see, in ClientProxy, object requestStore will contain all message that send to server.
In publish method, I will add requestId to message if it not existed before send to sever and create a subject contain callback and push to requestStore with key is requestId. This subject emit only one time and has timeout. Publish method will return a function that return this subject.
After that, I create a provider implement OnApplicationBootstrap named boostrap.ts.
This provider will implement onAny function of our socket. Whenever server receive new message, it will check if message contain requestId. If message contain requestId and requestId found in requestStore of clientProxy, then get the stored subject and call next function with data of message.
Now we can check our new client proxy. Send a greeting to server and wait response to display.
And server we can write a fake handler
Run your server and your app. Then go to browser at address:
http://localhost:3000/test-send
After 2 sec, server will response data.
{"requestParams":{"sendTime":1657866103828},"socketResponse":{"event":"test-request-response","data":{"youSend":{"sendTime":1657866103828,"requestId":"8675a58d-c25f-4fb1-88fd-8fc514b7d3ca"},"meResponse":1657866105845,"requestId":"8675a58d-c25f-4fb1-88fd-8fc514b7d3ca"}}}
You can open multiple chrome tabs to test if data response is the same with other.
Full code at: https://github.com/keyyuki/simple-req-res-nestjs-socketio.git
Thanks for your reading.
Story of implement socket.io-client: https://keyyuki.medium.com/implement-simple-socket-io-client-to-nestjs-microservice-7640e0dfb5ce