1

I am trying to create a websockets gateway in NestJS that responds to multiple paths. This is a requirement as what I am trying to build would replace an existing system. I am using WsAdapter as the underlying adapter for this.

The websockets paths could be expressed with slugs (e.g. /ws/:key) or regular expressions. The WebSocketGateway decorator, however, only accepts a single string and does not recognize slugs as such.

import { OnGatewayInit, SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
import { Logger } from '@nestjs/common';

@WebSocketGateway({path: '/ws/:key'})  // FIXME: ":key" should be treated as a slug here
export class ManagementGateway implements OnGatewayInit {
  private readonly logger = new Logger(ManagementGateway.name, false);

  afterInit(server: any): any {
    this.logger.debug('Websockets gateway initialized');
  }

  @SubscribeMessage('ctl')
  handle(client: any, data: unknown): void {
    this.logger.debug('ctl');
    // TODO
  }
}

The previous legacy implementation I am replacing does this with ws, express and regexp-based path matching.

Any hints or pointers would be greatly appreciated.

Manny
  • 783
  • 1
  • 9
  • 29
  • 1
    Use a custom WebSocketAdapter as a catch-all, then use the req.url, to route your request from your @WebSocketGateway() class. I have 2 projects that use this, but the code is too dirty to paste as an answer. – Uriel Apr 02 '22 at 16:03

0 Answers0