nest icon indicating copy to clipboard operation
nest copied to clipboard

Socket Gateway Dependency Injection Not Working

Open utkugetir opened this issue 1 year ago • 4 comments
trafficstars

Is there an existing issue for this?

  • [X] I have searched the existing issues

Current behavior

The dependencies do not get injected for the following code:

@UseFilters(new WsCatchAllFilter())
@WebSocketGateway({
  transports: ['websocket']
})
export class SocketGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  constructor(
    private readonly socketService: SocketService,
    private readonly logger: PinoLogger
  ) {
    logger.setContext(SocketGateway.name);
  }

  async handleConnection(client: Socket) {
    // Handle connection event
    try {
      this.logger.debug('New client connected. Verifying token...', { id: client.id });

      const isVerified = await this.socketService.verifyUser(client);
      if (!isVerified) {
        this.logger.debug('Client disconnected. Not authorized.', { id: client.id });
        client.disconnect();
      }

      this.logger.debug('Client connection success. Token verified.', { id: client.id });
      client.emit('connection', 'Successfully connected to server.');
    } catch (error) {
      client.disconnect();
      throw error;
    }
  }

  handleDisconnect(client: Socket) {
    // Handle disconnection event
    this.logger.debug('Client disconnected', { id: client.id });
  }
}

What I noticed is that constructor does not get called at all and produces the following error:

this.logger.debug('New client connected. Verifying token...', { id: client.id }); ^ TypeError: Cannot read properties of undefined (reading 'debug') at SocketGateway.handleConnection (/Users/utkuturkoglu/projects/turkoglu/phoenix-new/phoenix-api-gateway/src/socket/gateways/socket.gateway.ts:26:19) at Object.next (/Users/utkuturkoglu/projects/turkoglu/phoenix-new/phoenix-api-gateway/node_modules/@nestjs/websockets/web-sockets-controller.js:77:47) at ConsumerObserver.next (/Users/utkuturkoglu/projects/turkoglu/phoenix-new/phoenix-api-gateway/node_modules/rxjs/src/internal/Subscriber.ts:161:25) at SafeSubscriber._next (/Users/utkuturkoglu/projects/turkoglu/phoenix-new/phoenix-api-gateway/node_modules/rxjs/src/internal/Subscriber.ts:119:22) at SafeSubscriber.next (/Users/utkuturkoglu/projects/turkoglu/phoenix-new/phoenix-api-gateway/node_modules/rxjs/src/internal/Subscriber.ts:75:12) at /Users/utkuturkoglu/projects/turkoglu/phoenix-new/phoenix-api-gateway/node_modules/rxjs/src/internal/operators/distinctUntilChanged.ts:173:22 at OperatorSubscriber._next (/Users/utkuturkoglu/projects/turkoglu/phoenix-new/phoenix-api-gateway/node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts:70:13) at OperatorSubscriber.next (/Users/utkuturkoglu/projects/turkoglu/phoenix-new/phoenix-api-gateway/node_modules/rxjs/src/internal/Subscriber.ts:75:12) at /Users/utkuturkoglu/projects/turkoglu/phoenix-new/phoenix-api-gateway/node_modules/rxjs/src/internal/Subject.ts:68:20 at Object.errorContext (/Users/utkuturkoglu/projects/turkoglu/phoenix-new/phoenix-api-gateway/node_modules/rxjs/src/internal/util/errorContext.ts:29:5)

Minimum reproduction code

https://stackblitz.com/edit/nestjs-typescript-starter-hwu1qr?file=src%2Fsocket%2Fgateways%2Fsocket.gateway.ts

Steps to reproduce

Node Version: 20.10.0 "@nestjs/common": "10.4.1", "@nestjs/core": "10.4.1", "@nestjs/platform-socket.io": "^10.4.1", "@nestjs/websockets": "^10.4.1", "socket.io": "^4.7.5",

Expected behavior

Dependencies should be injected

Package

  • [ ] I don't know. Or some 3rd-party package
  • [ ] @nestjs/common
  • [ ] @nestjs/core
  • [ ] @nestjs/microservices
  • [ ] @nestjs/platform-express
  • [ ] @nestjs/platform-fastify
  • [ ] @nestjs/platform-socket.io
  • [ ] @nestjs/platform-ws
  • [ ] @nestjs/testing
  • [X] @nestjs/websockets
  • [ ] Other (see below)

Other package

No response

NestJS version

10.4.1

Packages versions

"@nestjs/common": "10.4.1",
"@nestjs/core": "10.4.1",
"@nestjs/platform-socket.io": "^10.4.1",
"@nestjs/websockets": "^10.4.1",
"socket.io": "^4.7.5",

Node.js version

20.10.0

In which operating systems have you tested?

  • [X] macOS
  • [ ] Windows
  • [ ] Linux

Other

No response

utkugetir avatar Sep 05 '24 12:09 utkugetir

I had to modify your reproduction significantly to even get it to install, compile, and start, and now I'm not sure how you expect us to test the gateway injection. Please provide a minimal reproduction that works and easily shows the problem.

jmcdo29 avatar Sep 05 '24 21:09 jmcdo29

I had to modify your reproduction significantly to even get it to install, compile, and start, and now I'm not sure how you expect us to test the gateway injection. Please provide a minimal reproduction that works and easily shows the problem.

Sorry about that, was in a rush. Updated the reproduction to be working

utkugetir avatar Sep 05 '24 21:09 utkugetir

this is just an idea on top of my head, will take out some time to actually test this

you need to use the Logger from @nestjs/common - since you have already configured the nestjs-pino in your app module as root logger, you should directly use the logger from nestjs.

import { Logger } from "@nestjs/common";

@UseFilters(new WsCatchAllFilter())
@WebSocketGateway({
  transports: ['websocket'],
})
export class SocketGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;
  private logger: Logger = new Logger(SocketGateway.name);

  // your methods here
}

give it a try and let me know

hassanmehdi98 avatar Sep 24 '24 12:09 hassanmehdi98

this is just an idea on top of my head, will take out some time to actually test this

you need to use the Logger from @nestjs/common - since you have already configured the nestjs-pino in your app module as root logger, you should directly use the logger from nestjs.

import { Logger } from "@nestjs/common";

@UseFilters(new WsCatchAllFilter())
@WebSocketGateway({
  transports: ['websocket'],
})
export class SocketGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;
  private logger: Logger = new Logger(SocketGateway.name);

  // your methods here
}

give it a try and let me know

Hi @hassanmehdi98

The issue is not logger, I have tried removing it and keeping only some other service injected, the issue persists. The problem is that it cannot inject any dependency

utkugetir avatar Oct 03 '24 17:10 utkugetir

Thank you for taking the time to submit your report! From the looks of it, this could be better discussed on our Discord. If you haven't already, please join here and send a new post in the #⁠ 🐈 nestjs-help forum. Make sure to include a link to this issue, so you don't need to write it all again. We have a large community of helpful members, who will assist you in getting this to work.

kamilmysliwiec avatar Nov 12 '24 10:11 kamilmysliwiec