Skip to content

Extended version of NestJs' WsAdapter that supports route parameters

License

Notifications You must be signed in to change notification settings

anotherpit/nestjs-ws-routable-adapter

Repository files navigation

WsRoutableAdapter for NestJS

Extended version of NestJs' WsAdapter that supports route parameters, similar to those of HTTP controllers.

Usage

gateway.ts

// Regular gateway definition
@WebSocketGateway({ path: '/' })
export class TestGateway {
  // Route-aware analog of @SubscribeMessage(...)
  @WsRouteSubscribe('ping/:param')
  onPing(
    @MessageBody() data,
    // New decorator to get the full route
    @WsRoute() route,
    // Route-aware analog of @Param(...)
    @WsRouteParam('param') param,
    @WsRouteParam('missingParam') missingParam,
  ) {
    return {
      event: 'pong',
      data: {
        data,
        route,
        param
      },
    };
  }
}

main.ts

async function bootstrap(): Promise<void> {
  // ...
  const app = await NestFactory.create(AppModule);
  app.useWebSocketAdapter(new WsRoutableAdapter(app));
  // ...
}

Now if you send

{ 
  "event": "ping/42", 
  "data": "data"
}

gateway will responde with

{
  "event": "pong",
  "data": {
    "data": "data",
    "route": "ping/42",
    "param": "42"
  }
}

Versioning

Since this library extends the build-in WsAdapter from the @nestjs/platform-ws package, versioning of this library will follow versioning of NestJs (patch versions might differ).

About

Extended version of NestJs' WsAdapter that supports route parameters

Resources

License

Stars

Watchers

Forks