1

Stack: Node.js + Express + TypeScript + Socket.io + tsyringe
Architecture: There's a WebServer class which creates the socket connection and then passes the io and the socket objects to the SocketController class . Both classes are decorated with @singleton() and the WebServer class is resolved in a top-level static function called main.
Problem: after multiple calls on socket methods the emission process (in response to listening methods on socket) occurs multiple times. It's actually incrementing by each time the method has been called. But the actual logic in the controller is only being performed once per each call.
Code:
Top-level module:

class Program {

  static Main(): void {
    const webServer = container.resolve(WebServer);
    const httpServer = webServer.StartServer();
    webServer.SocketConnection(httpServer);
  }
}

Program.Main();

WebServer class:

@singleton()
export class WebServer {

  constructor(private _socketController: SocketController) { }
  
  StartServer(): http.Server {
    // http server instantiation logic
    return httpServer;
  }

  SocketConnection(httpServer: http.Server): void {
    const io = new Server(httpServer);

    io.on('connection', (socket: Socket) => {
      this._socketController.SocketMethods(socket, io);
    });
  }
}

SocketController class:

@singleton()
export class SocketController {
  constructor(private _service: Service) { }

  SocketMethods(socket: Socket, io: Server): void {
    socket.on('method', async (params: any) => {
        const res = await this._service.ServiceMethodAsync(params);
        socket.emit('methodResponse', res);
      }
    });
  }
}
Omid
  • 301
  • 1
  • 2
  • 12

0 Answers0