januw a
januw a

Reputation: 2256

nestjs Gateways emit an event to all connected sockets

How to issue an event to all connected sockets?

    export class EventsGateway {

      @SubscribeMessage('message')

       async onEvent(client, data) {
        // The following is the use of `socket.io` to issue events to all connected sockets.
        // io.emit('message', data);
      }
    }

How do I perform this in nestjs?

Upvotes: 5

Views: 10483

Answers (1)

januw a
januw a

Reputation: 2256

NestJS allows you to create message listeners using decorators. Within this method, you are able to respond to the client by returning a WsResponse object.

However, NestJS also allows you to get the WebSocket instance using the WebSocketServer decorator.

To send an Event to all connected clients you will need to use the WebSocketServer decorator and use the native WebSocket instance to emit a message, like so:

import WebSocketServer from '@nestjs/websockets'

export class EventsGateway {
  @WebSocketServer() server;

  @SubscribeMessage('message')
  onEvent(client: any, payload: any): Observable<WsResponse<any>> | any {
    this.server.emit('message', payload);
  }
}

Upvotes: 10

Related Questions