nest icon indicating copy to clipboard operation
nest copied to clipboard

handleConnection method can conflict with WebSocket Gateway lifecycle hook

Open Emeryx opened this issue 1 year ago • 0 comments
trafficstars

Is there an existing issue for this?

  • [X] I have searched the existing issues

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

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

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?

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

Other

No response

Emeryx avatar May 27 '24 19:05 Emeryx