{"_id":"@0xelod/nestjs-websocket","name":"@0xelod/nestjs-websocket","dist-tags":{"latest":"0.1.7"},"versions":{"0.1.7":{"name":"@0xelod/nestjs-websocket","version":"0.1.7","description":"Websocket Client for NestJS based on ws","author":{"name":"Blockcoders Engineering","email":"hello@blockcoders.io"},"license":"Apache","homepage":"https://github.com/Taraxa-project/nestjs-websocket/blob/main/README.md","bugs":{"url":"https://github.com/Taraxa-project/nestjs-websocket/issues"},"repository":{"type":"git","url":"git+https://github.com/Taraxa-project/nestjs-websocket.git"},"main":"dist/index.js","engineStrict":false,"engines":{"node":"^10.24 || >=12.22 || >=14.17 || >=16.00"},"scripts":{"build":"rm -rf ./dist && tsc --p tsconfig.build.json","prepare":"npm run build","format":"prettier --write \"src/**/*.ts\"","lint":"eslint \"{src,apps,libs,test,__tests__}/**/*.ts\" --fix","lint:ci":"eslint \"{src,apps,libs,test,__tests__}/**/*.ts\"","test":"jest","test:watch":"jest --watch","test:cov":"jest --coverage","report":"cat ./coverage/lcov.info | coveralls","prepublishOnly":"npm run lint:ci & npm run test:cov"},"precommit":["lint:ci","test:cov"],"keywords":["ws","ws-client","websocket","websocket-client","websocket-protocol","websocket-library","websockets","nestjs","nest.js","nest"],"publishConfig":{"access":"public"},"dependencies":{"ws":"^8.2.3"},"devDependencies":{"@nestjs/common":"^8.0.11","@nestjs/core":"^8.0.11","@nestjs/platform-express":"^8.0.11","@nestjs/platform-fastify":"^8.0.11","@nestjs/platform-ws":"^8.0.11","@nestjs/testing":"^8.0.11","@nestjs/websockets":"^8.0.11","@types/express":"^4.17.13","@types/jest":"^27.0.2","@types/node":"^16.10.3","@types/supertest":"^2.0.11","@types/ws":"^8.2.0","@typescript-eslint/eslint-plugin":"^4.33.0","@typescript-eslint/parser":"^4.33.0","axios":">=0.22.0","coveralls":"^3.1.1","eslint":"^7.32.0","eslint-config-prettier":"^8.3.0","eslint-plugin-prettier":"^4.0.0","jest":"^27.2.4","nock":"^13.1.3","pre-commit":"^1.2.2","prettier":"^2.4.1","reflect-metadata":"^0.1.13","rxjs":"^7.4.0","supertest":"^6.1.6","ts-jest":"^27.0.5","ts-node":"^10.2.1","tsc-watch":"^4.5.0","tsconfig-paths":"^3.11.0","typescript":"^4.4.3"},"jest":{"verbose":true,"testTimeout":20000,"moduleFileExtensions":["js","json","ts"],"testRegex":".spec.ts$","transform":{"^.+\\.(t|j)s$":"ts-jest"},"coverageDirectory":"./coverage","collectCoverageFrom":["src/**/*.ts"],"coveragePathIgnorePatterns":["src/index.ts"],"coverageThreshold":{"global":{"branches":40,"functions":70,"lines":70,"statements":85}},"testEnvironment":"node"},"types":"./dist/index.d.ts","gitHead":"f8c5ae885bcb2220cb903259f24d975c00ad25f8","_id":"@0xelod/nestjs-websocket@0.1.7","_nodeVersion":"16.10.0","_npmVersion":"7.24.0","dist":{"integrity":"sha512-cue/CIJL6Mvjzetq6Nl/a39zP2bQTpoohrlkxEB0A5gy6oBrvJEmMqAkwbDAiqjUvwgt1Rl+OGXDK331Y+66zg==","shasum":"b18ae5917aa34288d839781168395573d707c1a2","tarball":"https://registry.npmjs.org/@0xelod/nestjs-websocket/-/nestjs-websocket-0.1.7.tgz","fileCount":24,"unpackedSize":40727,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIEJVNy0TCtBSTpog1WK97R7XgtS6oH/aoZmLERLV+J9FAiBUdbwNFtdqA9Fg7CqZkBTx/mqmzOT1UCSH2Bm4j8QZaw=="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjbiNMACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmqSWw//VaAIbpMY350qVDcFZ1Bz4TkHnbPB44iVQDglJKje9oKwtxPg\r\nvGVUNOPyfhxoBgyWpSn2sdBQH7aSVU+j2uBc3aN+fAvcgHXoTcT2tsKZ78u1\r\nlJ244E/JYAzpgCMvT1+m4fQQatZq1I9iwl5C8L2V/6X0lwPAqgYfZsT+qpiv\r\nR8+sJ6YMO8S2R5XpbY9uYtj5rXTdUerBsUq87V3ajfTBlnXWEB8ixfDFNeo0\r\nROqyty3/zwxR1QF6s8QVnyK0ohkw30suq/SC/0trvVpCdg5tFvoTEIQRVNJ/\r\nwMtKdfg9hBXaArNJKJtDSn5XRUSunIRzQgv8z3X9K0Mg3R2uoURprnrNFJLz\r\nHgS01dIf6r1x3V10ZUtnicdWCsszJHmBkVxcwW/TeLtmh5/SA2HgWu6H643Z\r\nEsO5AbmoHW5qkew8m27Tu9wv2Io8J30xqm66cEB5gP2dUARr+DQUVf9Ebec9\r\nnWgvwLXmu0ignsw9rFpIsa5T69vS6f7fbSOgigWqeqxyJbYBX0ksgPHn5AyF\r\nkxGCseDfF7/Gkwy95cXWLKIVlqBkX9zdPBGCw8CRJp4E/sQ7jqQ0rmPLpk5e\r\n5OEJl4Y1eA9HxffpQfUvhq3Q3BqLZatHraylrsjPgYoBeCCZ++2P5CbCV84y\r\n2J4o1U/TQLGErL/AxRhb9+9MNSYSf5pf3zE=\r\n=InPV\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"0xelod","email":"elod.varga@taraxa.io"},"directories":{},"maintainers":[{"name":"0xelod","email":"elod.varga@taraxa.io"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/nestjs-websocket_0.1.7_1668162380601_0.5744960616673229"},"_hasShrinkwrap":false}},"time":{"created":"2022-11-11T10:26:20.508Z","0.1.7":"2022-11-11T10:26:20.757Z","modified":"2022-11-11T10:26:20.973Z"},"maintainers":[{"name":"0xelod","email":"elod.varga@taraxa.io"}],"description":"Websocket Client for NestJS based on ws","homepage":"https://github.com/Taraxa-project/nestjs-websocket/blob/main/README.md","keywords":["ws","ws-client","websocket","websocket-client","websocket-protocol","websocket-library","websockets","nestjs","nest.js","nest"],"repository":{"type":"git","url":"git+https://github.com/Taraxa-project/nestjs-websocket.git"},"author":{"name":"Blockcoders Engineering","email":"hello@blockcoders.io"},"bugs":{"url":"https://github.com/Taraxa-project/nestjs-websocket/issues"},"license":"Apache","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) => {\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) => {\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<any, any> = {}\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<Record<any, any>> {\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","readmeFilename":"README.md"}