Emit websocket event from a NestJS controller or service

Viewed 4101

I am trying to listen to model change events in TypeORM through a subscriber, and broadcast an event each time a new one is inserted. While external clients receive the event, the gateway's @SubscribeMessage() method is not receiving it, which suggests that the sender is not getting the event. However, according to socket.io, the of('namespace').emit('event') should be received to any client, including the sender.

The gateway is injected to the subscriber service without any issue, and the gateway's server seems to be ready when I try to use it, but no event is emitted.

Running on NestJS 6.3.1, I have also tried emitting the event from the controller, with no results.

@WebSocketGateway({ namespace: '/posts' })
export class PostGateway {

  @WebSocketServer()
  server: Namespace;

  @SubscribeMessage('create')
  handleMessage(client: Socket, payload: Post): void {
    console.log('handling', payload);
  }

}
@Injectable()
export class PostSubscriber implements EntitySubscriberInterface<Post> {

  private socket: Namespace;

  constructor(
    @InjectConnection() readonly connection: Connection,
    private readonly gateway: PostGateway,
  ) {
    connection.subscribers.push(this);
    this.socket = gateway.server;
  }

  listenTo() {
    return Measurement;
  }

  afterInsert(event: InsertEvent<Post>): void {
    this.gateway.server.emit('create', event.entity);
  }

}

0 Answers
Related