socket.ionestjsnestjs-gateways

Custom decorator not being invoked on socket message handler (NestJS, SocketIO)


In app.gateway.ts, I have the following event handler:

@SubscribeMessage<TClientToServerEvents>('event')
  async handleRefreshCheck(
    @SocketContext() ctx: SocketContextDTO,
    @ConnectedSocket() socket: TSocket,
  ) {
    this.logger.log({
      message: 'Socket received event',
      ctx,
      meta: {
        socketData: {
          socketID: socket.id,
          handshake: socket.handshake,
          user: socket.data,
        },
      },
    });
    try {
      await this.service.logic(ctx);
    } catch (err) {
      this.logger.error({
        message: err.message,
        ctx,
      });
      throw new InternalServerErrorException();
    }
  }

socket-context.decorator.ts

export const SocketContext = createParamDecorator(
  (_: unknown, ctx: ExecutionContext): SocketContextDTO => {
    console.log('INVOKED'); // !! THIS LOG STATEMENT IS NOT PRINTING
    const socket = ctx.switchToWs().getClient();
    const socketContext = createSocketContextDTO(socket);
    return socketContext;
  },
);

I can't figure out why the @SocketContext() decorator isn't being invoked. The ConnectedSocket() decorator returns with no issues.

This is a recent development after refactoring other areas of the codebase, but the socket logic hasn't changed.

Thanks in advance for any suggestions!


Solution

  • I solved this by assigning the ctx variable in the body of the function. It's strange that I got away with using it before, but I think it has to do with createParamDecorator being intended as an HTTP route decorator constructor.

    New code:

    @SubscribeMessage<TClientToServerEvents>('event')
      async handleRefreshCheck(
        @ConnectedSocket() socket: TSocket,
      ) {
          const ctx = createSocketContextDTO(socket); 
          // ...
        }