{"id":19319664,"url":"https://github.com/blockcoders/nestjs-websocket","last_synced_at":"2025-04-22T17:31:57.050Z","repository":{"id":46972945,"uuid":"402891809","full_name":"blockcoders/nestjs-websocket","owner":"blockcoders","description":"Websocket Client for NestJS based on ws","archived":false,"fork":false,"pushed_at":"2022-11-11T10:01:48.000Z","size":334,"stargazers_count":22,"open_issues_count":3,"forks_count":12,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-04-02T02:22:27.609Z","etag":null,"topics":["nest","nestjs","websocket","websocket-client","websocket-library","websocket-protocol","websockets","ws","ws-client"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/blockcoders.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-09-03T20:35:29.000Z","updated_at":"2025-02-15T15:19:10.000Z","dependencies_parsed_at":"2023-01-22T00:01:59.101Z","dependency_job_id":null,"html_url":"https://github.com/blockcoders/nestjs-websocket","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blockcoders%2Fnestjs-websocket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blockcoders%2Fnestjs-websocket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blockcoders%2Fnestjs-websocket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/blockcoders%2Fnestjs-websocket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/blockcoders","download_url":"https://codeload.github.com/blockcoders/nestjs-websocket/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249715888,"owners_count":21315058,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["nest","nestjs","websocket","websocket-client","websocket-library","websocket-protocol","websockets","ws","ws-client"],"created_at":"2024-11-10T01:24:45.116Z","updated_at":"2025-04-22T17:31:56.650Z","avatar_url":"https://github.com/blockcoders.png","language":"TypeScript","readme":"# NestJS-Websocket\n\n[![npm](https://img.shields.io/npm/v/nestjs-websocket)](https://www.npmjs.com/package/nestjs-websocket)\n[![CircleCI](https://circleci.com/gh/blockcoders/nestjs-websocket/tree/main.svg?style=svg)](https://circleci.com/gh/blockcoders/nestjs-websocket/tree/main)\n[![Coverage Status](https://coveralls.io/repos/github/blockcoders/nestjs-websocket/badge.svg?branch=main)](https://coveralls.io/github/blockcoders/nestjs-websocket?branch=main)\n[![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/nestjs-websocket)](https://snyk.io/test/github/blockcoders/nestjs-websocket)\n[![supported platforms](https://img.shields.io/badge/platforms-Express%20%26%20Fastify-green)](https://img.shields.io/badge/platforms-Express%20%26%20Fastify-green)\n\nWebsocket Client for NestJS based on [ws](https://www.npmjs.com/package/ws)\n\n## Install\n\n```sh\nnpm i nestjs-websocket\n```\n\n## Register module\n\n### Configuration params\n\n`nestjs-websocket` can be configured with this options:\n\n```ts\n/**\n * WebSocket Client options\n * @see {@link https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocket}\n */\ninterface WebSocketModuleOptions {\n  /**\n   * Required parameter a URL to connect to.\n   * such as http://localhost:3000 or wss://localhost:3000.\n   */\n  url: string | URL;\n\n  /**\n   * Optional parameter a list of subprotocols.\n   */\n  protocols?: string | string[]\n  \n  /**\n   * Optional parameter a client or http request options.\n   */\n  options?: ClientOptions | ClientRequestArgs\n}\n```\n\n### Synchronous configuration\n\nUse `WebSocketModule.forRoot` method with [Options interface](#configuration-params):\n\n```ts\nimport { WebSocketModule } from 'nestjs-websocket'\n\n@Module({\n  imports: [\n    WebSocketModule.forRoot({\n      url: 'ws://localhost:3000',\n      protocols: ['foo', 'bar'],\n      options: {\n        followRedirects: false,\n        handshakeTimeout: 10000,\n        maxPayload: 2000000,\n        maxRedirects: 10,\n        origin: 'http:/example.com',\n        perMessageDeflate: false,\n        protocolVersion: 1,\n        skipUTF8Validation: false,\n      },\n    }),\n  ],\n  ...\n})\nclass MyModule {}\n```\n\n### Asynchronous configuration\n\nWith `WebSocketModule.forRootAsync` you can, for example, import your `ConfigModule` and inject `ConfigService` to use it in `useFactory` method.\n\n`useFactory` should return object with [Options interface](#configuration-params)\n\nHere's an example:\n\n```ts\nimport { Module, Injectable } from '@nestjs/common'\nimport { WebSocketModule } from 'nestjs-websocket'\n\n@Injectable()\nclass ConfigService {\n  public readonly url = 'ws://localhost:3000'\n}\n\n@Module({\n  providers: [ConfigService],\n  exports: [ConfigService]\n})\nclass ConfigModule {}\n\n@Module({\n  imports: [\n    WebSocketModule.forRootAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: (config: ConfigService) =\u003e {\n        return {\n          url: config.url,\n        }\n      },\n    }),\n  ],\n  ...\n})\nclass MyModule {}\n```\n\nOr you can just pass `ConfigService` to `providers`, if you don't have any `ConfigModule`:\n\n```ts\nimport { Module, Injectable } from '@nestjs/common'\nimport { WebSocketModule } from 'nestjs-websocket'\n\n@Injectable()\nclass ConfigService {\n  public readonly url = 'ws://localhost:3000'\n}\n\n@Module({\n  imports: [\n    WebSocketModule.forRootAsync({\n      providers: [ConfigService],\n      inject: [ConfigService],\n      useFactory: (config: ConfigService) =\u003e {\n        return {\n          url: config.url,\n        }\n      },\n    }),\n  ],\n  controllers: [TestController]\n})\nclass TestModule {}\n```\n\n## WebSocketClient\n\n`WebSocketClient` implements a [WebSocket](https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocket). So if you are familiar with it, you are ready to go.\n\n```ts\nimport { Injectable } from '@nestjs/common'\nimport {\n  InjectWebSocketProvider,\n  WebSocketClient,\n  OnOpen,\n  OnMessage,\n} from 'nestjs-websocket';\n\n@Injectable()\nclass TestService {\n  private data: Record\u003cany, any\u003e = {}\n\n  constructor(\n    @InjectWebSocketProvider()\n    private readonly ws: WebSocketClient,\n  ) {}\n\n  @OnOpen()\n  onOpen() {\n    this.ws.send(JSON.stringify(eventData))\n  }\n\n  @OnMessage()\n  message(data: WebSocketClient.Data) {\n    this.data = JSON.parse(data.toString())\n  }\n\n  async getData(): Promise\u003cRecord\u003cany, any\u003e\u003e {\n    return this.data\n  }\n}\n```\n\n## Websocket Events\n\n### EventListener\n\n`@EventListener` decorator will handle any event emitted from websocket server.\n\n```ts\nimport { Injectable } from '@nestjs/common'\nimport { ClientRequest, IncomingMessage } from 'http'\nimport {\n  EventListener\n} from 'nestjs-websocket';\n\n@Injectable()\nclass TestService {\n  @EventListener('open')\n  open() {\n    console.log('The connection is established.')\n  }\n  \n  @EventListener('ping')\n  ping(data: Buffer) {\n    console.log(`A ping ${data.toString()} is received from the server.`)\n  }\n  \n  @EventListener('unexpected-response')\n  unexpectedResponse(request: ClientRequest, response: IncomingMessage) {\n    console.log(`The server response ${response} is not the expected one.`)\n  }\n  \n  @EventListener('upgrade')\n  upgrade(response: IncomingMessage) {\n    console.log(`Response headers ${response} are received from the server as part of the handshake.`)\n  }\n}\n```\n\n### OnOpen\n\n`@OnOpen` is a shortcut for `@EventListener('open')`. Event emitted when the connection is established.\n\n```ts\nimport { Injectable } from '@nestjs/common'\nimport {\n  OnOpen\n} from 'nestjs-websocket';\n\n@Injectable()\nclass TestService {\n  @OnOpen()\n  open() {\n    console.log('The connection is established.')\n  }\n}\n```\n\n### OnClose\n\n`@OnClose` is a shortcut for `@EventListener('close')` Event emitted when the connection is closed. `code` property is a numeric value for status code explaining why the connection has been closed. `reason` is a Buffer containing a human-readable string explaining why the connection has been closed.\n\n```ts\nimport { Injectable } from '@nestjs/common'\nimport {\n  OnClose\n} from 'nestjs-websocket';\n\n@Injectable()\nclass TestService {\n  @OnClose()\n  close(code: number, reason: string) {\n    console.log(`The connection is closed. Reason: ${code} - ${reason}`)\n  }\n}\n```\n\n### OnError\n\n`@OnError` is a shortcut for `@EventListener('error')`. Event emitted when an error occurs. Errors may have a [.code](https://github.com/websockets/ws/blob/HEAD/doc/ws.md#ws-error-codes) property.\n\n```ts\nimport { Injectable } from '@nestjs/common'\nimport {\n  OnError\n} from 'nestjs-websocket';\n\n@Injectable()\nclass TestService {\n  @OnError()\n  error(err: Error) {\n    console.log(`An error occurs: ${err}`)\n  }\n}\n```\n\n### OnMessage\n\n`@OnMessage` is a shortcut for `@EventListener('message')`. Event emitted when a message is received. `data` is the message content.\n\n```ts\nimport { Injectable } from '@nestjs/common'\nimport {\n  OnMessage\n} from 'nestjs-websocket';\n\n@Injectable()\nclass TestService {\n  @OnMessage()\n  message(data: WebSocketClient.Data) {\n    console.log(`Data received: ${JSON.parse(data.toString())}`)\n  }\n}\n```\n\n## Testing a class that uses @InjectWebSocketProvider\n\nThis package exposes a `getWebSocketToken()` function that returns a prepared injection token based on the provided context.\nUsing this token, you can easily provide a mock implementation of the [ws](https://github.com/websockets/ws) using any of the standard custom provider techniques, including useClass, useValue, and useFactory.\n\n```ts\nconst module: TestingModule = await Test.createTestingModule({\n  providers: [\n    MyService,\n    {\n      provide: getWebSocketToken(),\n      useValue: mockProvider,\n    },\n  ],\n}).compile();\n```\n\n## Change Log\n\nSee [Changelog](CHANGELOG.md) for more information.\n\n## Contributing\n\nContributions welcome! See [Contributing](CONTRIBUTING.md).\n\n## Authors\n\n- [**Jose Ramirez**](https://github.com/0xslipk)\n- [**Ana Riera**](https://github.com/AnnRiera)\n\n## License\n\nLicensed under the Apache 2.0 - see the [LICENSE](LICENSE) file for details.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fblockcoders%2Fnestjs-websocket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fblockcoders%2Fnestjs-websocket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fblockcoders%2Fnestjs-websocket/lists"}