Giter Club home page Giter Club logo

nestjs-websocket's Introduction

NestJS-Websocket

npm CircleCI Coverage Status vulnerabilities supported platforms

Websocket Client for NestJS based on ws

Install

npm i nestjs-websocket

Register module

Configuration params

nestjs-websocket can be configured with this options:

/**
 * WebSocket Client options
 * @see {@link https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocket}
 */
interface WebSocketModuleOptions {
  /**
   * Required parameter a URL to connect to.
   * such as http://localhost:3000 or wss://localhost:3000.
   */
  url: string | URL;

  /**
   * Optional parameter a list of subprotocols.
   */
  protocols?: string | string[]
  
  /**
   * Optional parameter a client or http request options.
   */
  options?: ClientOptions | ClientRequestArgs
}

Synchronous configuration

Use WebSocketModule.forRoot method with Options interface:

import { WebSocketModule } from 'nestjs-websocket'

@Module({
  imports: [
    WebSocketModule.forRoot({
      url: 'ws://localhost:3000',
      protocols: ['foo', 'bar'],
      options: {
        followRedirects: false,
        handshakeTimeout: 10000,
        maxPayload: 2000000,
        maxRedirects: 10,
        origin: 'http:/example.com',
        perMessageDeflate: false,
        protocolVersion: 1,
        skipUTF8Validation: false,
      },
    }),
  ],
  ...
})
class MyModule {}

Asynchronous configuration

With WebSocketModule.forRootAsync you can, for example, import your ConfigModule and inject ConfigService to use it in useFactory method.

useFactory should return object with Options interface

Here's an example:

import { Module, Injectable } from '@nestjs/common'
import { WebSocketModule } from 'nestjs-websocket'

@Injectable()
class ConfigService {
  public readonly url = 'ws://localhost:3000'
}

@Module({
  providers: [ConfigService],
  exports: [ConfigService]
})
class ConfigModule {}

@Module({
  imports: [
    WebSocketModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        return {
          url: config.url,
        }
      },
    }),
  ],
  ...
})
class MyModule {}

Or you can just pass ConfigService to providers, if you don't have any ConfigModule:

import { Module, Injectable } from '@nestjs/common'
import { WebSocketModule } from 'nestjs-websocket'

@Injectable()
class ConfigService {
  public readonly url = 'ws://localhost:3000'
}

@Module({
  imports: [
    WebSocketModule.forRootAsync({
      providers: [ConfigService],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        return {
          url: config.url,
        }
      },
    }),
  ],
  controllers: [TestController]
})
class TestModule {}

WebSocketClient

WebSocketClient implements a WebSocket. So if you are familiar with it, you are ready to go.

import { Injectable } from '@nestjs/common'
import {
  InjectWebSocketProvider,
  WebSocketClient,
  OnOpen,
  OnMessage,
} from 'nestjs-websocket';

@Injectable()
class TestService {
  private data: Record<any, any> = {}

  constructor(
    @InjectWebSocketProvider()
    private readonly ws: WebSocketClient,
  ) {}

  @OnOpen()
  onOpen() {
    this.ws.send(JSON.stringify(eventData))
  }

  @OnMessage()
  message(data: WebSocketClient.Data) {
    this.data = JSON.parse(data.toString())
  }

  async getData(): Promise<Record<any, any>> {
    return this.data
  }
}

Websocket Events

EventListener

@EventListener decorator will handle any event emitted from websocket server.

import { Injectable } from '@nestjs/common'
import { ClientRequest, IncomingMessage } from 'http'
import {
  EventListener
} from 'nestjs-websocket';

@Injectable()
class TestService {
  @EventListener('open')
  open() {
    console.log('The connection is established.')
  }
  
  @EventListener('ping')
  ping(data: Buffer) {
    console.log(`A ping ${data.toString()} is received from the server.`)
  }
  
  @EventListener('unexpected-response')
  unexpectedResponse(request: ClientRequest, response: IncomingMessage) {
    console.log(`The server response ${response} is not the expected one.`)
  }
  
  @EventListener('upgrade')
  upgrade(response: IncomingMessage) {
    console.log(`Response headers ${response} are received from the server as part of the handshake.`)
  }
}

OnOpen

@OnOpen is a shortcut for @EventListener('open'). Event emitted when the connection is established.

import { Injectable } from '@nestjs/common'
import {
  OnOpen
} from 'nestjs-websocket';

@Injectable()
class TestService {
  @OnOpen()
  open() {
    console.log('The connection is established.')
  }
}

OnClose

@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.

import { Injectable } from '@nestjs/common'
import {
  OnClose
} from 'nestjs-websocket';

@Injectable()
class TestService {
  @OnClose()
  close(code: number, reason: string) {
    console.log(`The connection is closed. Reason: ${code} - ${reason}`)
  }
}

OnError

@OnError is a shortcut for @EventListener('error'). Event emitted when an error occurs. Errors may have a .code property.

import { Injectable } from '@nestjs/common'
import {
  OnError
} from 'nestjs-websocket';

@Injectable()
class TestService {
  @OnError()
  error(err: Error) {
    console.log(`An error occurs: ${err}`)
  }
}

OnMessage

@OnMessage is a shortcut for @EventListener('message'). Event emitted when a message is received. data is the message content.

import { Injectable } from '@nestjs/common'
import {
  OnMessage
} from 'nestjs-websocket';

@Injectable()
class TestService {
  @OnMessage()
  message(data: WebSocketClient.Data) {
    console.log(`Data received: ${JSON.parse(data.toString())}`)
  }
}

Testing a class that uses @InjectWebSocketProvider

This package exposes a getWebSocketToken() function that returns a prepared injection token based on the provided context. Using this token, you can easily provide a mock implementation of the ws using any of the standard custom provider techniques, including useClass, useValue, and useFactory.

const module: TestingModule = await Test.createTestingModule({
  providers: [
    MyService,
    {
      provide: getWebSocketToken(),
      useValue: mockProvider,
    },
  ],
}).compile();

Change Log

See Changelog for more information.

Contributing

Contributions welcome! See Contributing.

Authors

License

Licensed under the Apache 2.0 - see the LICENSE file for details.

nestjs-websocket's People

Contributors

0xslipk avatar annriera avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

nestjs-websocket's Issues

How can I use Multiple Websocket Client with your great package?

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

I import two WebSocketModule in each different module like below code.

// upbit.module.ts
import { Module } from '@nestjs/common';
import { UpbitService } from './upbit.service';
import { WebSocketModule } from 'nestjs-websocket';
import { UpbitWebsocketClient } from './upbitWebsocketClient';

@Module({
  imports: [
    WebSocketModule.forRoot({
      url: 'wss://api.upbit.com/websocket/v1',
    }),
  ],
  providers: [UpbitService, UpbitWebsocketClient],
  exports: [UpbitWebsocketClient],
})
export class UpbitModule {}
// binance.module.ts
import { Module } from '@nestjs/common';
import { WebSocketModule } from 'nestjs-websocket';
import { BinanceService } from './binance.service';
import { BinanceWebsocketClient } from './binanceWebsocketClient';

@Module({
  imports: [
    WebSocketModule.forRoot({
      url: 'wss://stream.binance.com:9443/ws/btcusdt@trade',
    }),
  ],
  providers: [BinanceService, BinanceWebsocketClient],
  exports: [BinanceWebsocketClient],
})
export class BinanceModule {}

Expected behavior

I expected that I can use both websocket clients because I imported two websocket clients which have different url in each module(upbit.module, binance.module).

But I can only use binance websocket client.

Minimal reproduction of the problem with instructions

I don't have it.

What is the motivation / use case for changing the behavior?

We can get the information from many different WebSocket Clients.

Environment


Nest version: X.Y.Z
Nest WebSocket: X.Y.Z

 
For Tooling issues:
- Node version: v16.16.0
- Platform: Mac
- Server: Express

Others:

Reconnect when connect closed

i used your module. However, I have a problem as follows, when the connection to the server side is closed, now I don't know how to reopen that connection. I'd love you feedback guys :D

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.