nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
66.9k stars 7.55k forks source link

handleConnection method can conflict with WebSocket Gateway lifecycle hook #13618

Closed Emeryx closed 3 months ago

Emeryx commented 3 months ago

Is there an existing issue for this?

Current behavior

When using a WebSocket gateway in NestJS, the handleConnection method is reserved for lifecycle handling. However, there is no clear documentation indicating this reservation. If a user defines their own handleConnection method, it gets called on every connection, regardless of the @SubscribeMessage decorator.

This is also relevant to methods named handleDisconnect, Which I assume activate when the client disconnects, Though I only tried handleConnection.

@WebSocketGateway()
export class SocketGatewayExample {
    ...
    @SubscribeMessage('random-message')
    async handleConnection(...){ 
    // Always runs upon connection to socket
}

Minimum reproduction code

https://stackblitz.com/edit/typescript-gvcfjr?file=events.gateway.ts

Steps to reproduce

  1. Create a WebSocket gateway.
  2. Define a method named handleConnection with the @SubscribeMessage decorator.
  3. Observe that handleConnection is invoked on every connection attempt, not just for specific subscribed messages.

Expected behavior

A clear warning should be provided if handleConnection is defined, indicating its reserved nature for WebSocket lifecycle management. Alternatively, the documentation should clearly state the reservation of the handleConnection method to prevent such conflicts.

Package

Other package

No response

NestJS version

10.0.0

Packages versions

[System Information]
OS Version     : Windows 10.0.19045
NodeJS Version : v20.11.1
NPM Version    : 10.5.0 

[Nest CLI]
Nest CLI Version : 10.3.2

[Nest Platform Information]
platform-socket.io version : 10.3.8
platform-express version   : 10.3.8
websockets version         : 10.3.8
schematics version         : 10.1.1
mongoose version           : 10.0.6
testing version            : 10.3.8
common version             : 10.3.8
core version               : 10.3.8
cli version                : 10.3.2

Node.js version

No response

In which operating systems have you tested?

Other

No response

kamilmysliwiec commented 3 months ago

That's the expected behavior. If you feel that our documentation is misleading, please create a PR here https://github.com/nestjs/docs.nestjs.com/edit/master/content/websockets/gateways.md - contributions are more than welcome