node.jssocket.ionestjsbackendreal-time

Fetch a specific socket from sockets list - NestJs


I need to fetch a specific socket from sockets list with Nests , the way I use in the code below, but I don't want to pull all the sockets in to a list then search for the socket in it , is there away to directly search and fetch the required socket instead of using "fetchSockets()" method?

 @WebSocketServer()
  server: Server = new Server<ServerToClientEvents, ClientToServerEvents>();

@SubscribeMessage('event')
  async handelInitial(@MessageBody() data: any): Promise<void> {
 
    const array = await this.server.sockets.fetchSockets();
    const sockest = array.find((e)=>e.id==='required socket id')

}

Solution

  • You can use const sockets = await io.in(theSocketId).fetchSockets(); as described here: https://socket.io/docs/v4/server-instance/#fetchsockets

    In your Nest app this would look like this: await this.server.in('socket id').fetchSockets().