Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Socket Gateway Dependency Injection Not Working #13948

Open
3 of 15 tasks
utkugetir opened this issue Sep 5, 2024 · 4 comments
Open
3 of 15 tasks

Socket Gateway Dependency Injection Not Working #13948

utkugetir opened this issue Sep 5, 2024 · 4 comments
Labels
needs clarification needs triage This issue has not been looked into

Comments

@utkugetir
Copy link

utkugetir commented Sep 5, 2024

Is there an existing issue for this?

  • 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
  • @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?

  • macOS
  • Windows
  • Linux

Other

No response

@utkugetir utkugetir added the needs triage This issue has not been looked into label Sep 5, 2024
@jmcdo29
Copy link
Member

jmcdo29 commented Sep 5, 2024

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.

@utkugetir
Copy link
Author

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

@hassanmehdi98
Copy link

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

@utkugetir
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs clarification needs triage This issue has not been looked into
Projects
None yet
Development

No branches or pull requests

3 participants