hexabot/api/src/websocket
2024-10-26 12:02:39 +01:00
..
decorators fix: remove non compliant OSD license term 2024-09-29 13:02:28 +01:00
pipes fix: remove non compliant OSD license term 2024-09-29 13:02:28 +01:00
services fix: remove non compliant OSD license term 2024-09-29 13:02:28 +01:00
storage fix: remove non compliant OSD license term 2024-09-29 13:02:28 +01:00
utils fix: remove non compliant OSD license term 2024-09-29 13:02:28 +01:00
README.md feat: initial commit 2024-09-10 10:50:11 +01:00
types.ts fix: remove non compliant OSD license term 2024-09-29 13:02:28 +01:00
websocket.gateway.spec.ts feat: rename live chat tester to console 2024-10-23 06:20:39 +01:00
websocket.gateway.ts fix: refactor session store 2024-10-26 12:02:39 +01:00
websocket.module.ts fix: remove non compliant OSD license term 2024-09-29 13:02:28 +01:00

NestJS WebSocket Implementation

This README provides documentation for this custom WebSocket service implementation designed to handle real-time communication efficiently. The service uses custom decorators and dynamic event dispatching to manage WebSocket connections and route events within a NestJS application as a Restful API.

Features

  • Dynamic Event Handling: Methods can be dynamically tagged to handle specific WebSocket events using custom decorators.
  • Robust Exception Handling: Integrated exception handling to manage both expected and unexpected errors gracefully.
  • Extensible Request Handling: Enhanced request handling through the SocketRequest class, which supports query parameters and other HTTP-like features.

Components

The implementation consists of several components:

  • SocketEventMetadataStorage: Stores event handler metadata.
  • Socket[Get|Post|Put|...] Decorators: Decorates methods to handle specific HTTP verb events.
  • SocketRequest & SocketResponse Classes: Parses incoming WebSocket messages and creates synthetic request and response objects.
  • SocketEventDispatcherService: Dispatches events to appropriate handlers.
  • Exception Handling: Manages errors and exceptions during WebSocket communication.

Configuring WebSocket Handlers

By using "get" as event name, the message to be sent using a socket io client would have the following payload :

{ "method": "get", "headers": {}, "data": {}, "url": "/example?id=1" }

This will eventually trigger a event "hook:socket:request:get" which will be intercepted by the appropriate listener(s) detected by the SocketEventDispatcherService. Decorate service methods in your NestJS services using the SocketGet decorator to handle specific WebSocket events:

  @SocketGet('/example')
  handleExample(
    @SocketReq() req: SocketRequest,
    @SocketRes() res: SocketResponse,
  ) {
    if (!req.query.id) {
        throw new NotFoundException('Id not found')
    }
    console.log('Received : ', req.body);
    res.status(200).send('Hello !');
  }