Search code examples
websocketsocket.ionestjs

How to pass socket client connection from nestjs service


I want to pass the connected socket client to nest js service. I referred to this question https://stackoverflow.com/question.....but I can't understand how to pass the client:Socket from my service.

I have a bull queue which handles some file processing tasks. once the file processing is completed. I want to notify that to the user who sent that file. below is my WebSocket gateway. In here notifyJobStatus is getting called once the job is done. but I want to send it to a particular client. for that, I need to access the client from my service. then I can modify the method to something like this notifyJobStatus(status: string, client: Socket).please correct me if this approach is wrong.

export class NotificationsService
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  @WebSocketServer() server: Server;
  private readonly logger = new Logger(NotificationsService.name);

  notifyJobStatus(status: string) {
    //client.broadcast.to(client.id).emit('JobStatus', status);
    this.server.emit('JobStatus', status);
  }

  afterInit() {
    this.logger.log('Websocket Server Started,Listening on Port:3006');
  }

  handleDisconnect(client: Socket) {
    console.log(`Client disconnected: ${client.id}`);
  }

  handleConnection(client: Socket, ...args: any[]) {
    console.log(`Client connected: ${client.id}`);
  }
}

Solution

  • this worked for me, It should work for you also. Let's say we have notifyModule and I want to call the queue in OrderModule

    1. I exported the NotifyConsumer in the module
    2. I then registered the queue in the Order Module, don't forget, it's registered in your NotifyModule also.
        BullModule.registerQueue({
          name: 'order-queue',
        }),
        BullModule.registerQueue({
          name: 'notify-queue',
        }),
    
    

    Note: The order-queue has nothing to do with the answer, I just copied my code for you.

    Then, I imported the notify-queue in the order controller file that I needed it

        @InjectQueue('notify-queue') private notifyQueue: Queue,
    
    

    Lastly, I used it and it worked

        // send latest notification
          await this.notifyQueue.add('notify', {
            ...
          });