1

How do I in nestjs create a client connection to a web socket server.

For example: there is a web socket or socket.io server that sends a message to all its clients every second.

How do I properly connect to this server in nestjs and listen to message events from it. Do I have to create a special Adapter for my WebSocketGateway to be a client? And is it possible to make Websotsketgateva a client at all? If not, what is the right way to do it?

Serhiy
  • 21
  • 2

1 Answers1

1

I can suggest U 2 way to do it

1: create your adapter that implement WebSocketAdapter. Then you can use @SocketGateway and @SubscribeMessage. You can read more at: Connect NestJS to a websocket server

2: create one provider implement OnApplicationBootstrap. In this provider, you install your socket client, and fire event from it to EventEmitor.


@Injectable()
export class IoClientGatewayBootstrap implements OnApplicationBootstrap {
  @Inject(IoClient)
  private ioClient: IoClient;
  @Inject(GLOBAL_PROVIDER.LOCAL_EVENT_EMITOR)
  private localEventEmitor: LocalEventEmitorInterface;

  onApplicationBootstrap() {
    console.log('run');

    this.connect();
  }

  connect = () => {
    const connection = io(AppConfig.SOCKET_SERVER_URL);

    connection.on('connect', () => {
      console.log('ok connect');
    });

    connection.on('disconnect', (reason) => {
      console.log('disconnect', reason);
    });

    // swap socket event to local event
    connection.onAny((eventName: string, ...args) => {
      console.log(eventName);
      this.localEventEmitor.emit(eventName, args);
    });

    this.ioClient.setIoClient(connection);
  };
}

where localEventEmitor is a service implement EventEmitter2 (https://docs.nestjs.com/techniques/events)

import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { LocalEventEmitorInterface } from './local-event-emitor.interface';

@Injectable()
export class LocalEventEmitor implements LocalEventEmitorInterface {
  constructor(private eventEmitter: EventEmitter2) {}

  emit = (
    event: string,
    data: any,
  ) => {
    this.eventEmitter.emit(event, data);
  };

  
}

and now you can listen socket event as local event in any module you want

 @OnEvent('test-my-event')
  handleEvent(event: unknown) {
    console.log(event);
  }