dimanche 27 novembre 2022

NestJS websocket gateway pattern for multiple features

I am in the process of building a NestJS application that will be using WebSockets to communicate with the client. However, I am having trouble trying to determine what the pattern is for utilizing the @WebSocketGateway decorator between multiple features or what the suggested best practices are.

It appears that my options are to either encapsulate the functionality for all of my features (bookmarks, chats, posts) into a singular @WebSocketGateway class (i.e. app.gateway.ts) or to create a gateway for each of my features (i.e. bookmark.gateway.ts, chat.gateway.ts, etc...).

My current bookmark gateway appears like this

import {
  MessageBody,
  OnGatewayConnection,
  OnGatewayDisconnect,
  OnGatewayInit,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket, Namespace } from 'socket.io';
import { Logger, OnModuleInit } from '@nestjs/common';

@WebSocketGateway({ namespace: 'bookmarks' })
export class BookmarkGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  private readonly logger = new Logger(BookmarkGateway.name);

  @WebSocketServer() io: Namespace;

  afterInit(server: Server): any {
    this.logger.log('Websocket Gateway initialized');
  }

  handleConnection(client: Socket): any {
    const sockets = this.io.sockets;

    this.logger.log(`WS Client with id: ${client.id}  connected!`);
    this.logger.debug(`Number of connected sockets ${sockets.size}`);
  }

  handleDisconnect(client: Socket): any {
    const sockets = this.io.sockets;

    this.logger.log(`WS Client with id: ${client.id}  disconnected!`);
    this.logger.debug(`Number of connected sockets ${sockets.size}`);
  }

  @SubscribeMessage('newMessage')
  onNewMessage(@MessageBody() body: any) {
    console.log(body);
  }
}

The first approach seems like it would go against the prescribed structure for a Nest application however the second approach requires a lot of code duplication for implementation of the connect and disconnect interfaces as well as creating multiple connections.

I did find another post pointing at the creation of a global gateway however it appears that it only provides the ability to emit messages by exporting the WebSocketServer and not the ability to SubscribeMessage.

Every other example I have found creates the gateway as part of the feature but this seems quite duplicitous in nature.

I was wondering if someone could point me in the right direction as to the accepted practice for implementing WebSockets across multiple features in NestJS?

Aucun commentaire:

Enregistrer un commentaire