@nestjs/websockets

  • Version 11.1.8
  • Published
  • 84.4 kB
  • 3 dependencies
  • MIT license

Install

npm i @nestjs/websockets
yarn add @nestjs/websockets
pnpm add @nestjs/websockets

Overview

Nest - modern, fast, powerful node.js web framework (@websockets)

Index

Functions

function Ack

Ack: () => ParameterDecorator;
  • WebSockets ack parameter decorator. Extracts the ack callback function from the arguments of a ws event.

    This decorator signals to the framework that the ack callback will be handled manually within the method, preventing the framework from automatically sending an acknowledgement based on the return value.

    Example 1

    @SubscribeMessage('events')
    onEvent(
    @MessageBody() data: string,
    @Ack() ack: (response: any) => void
    ) {
    // Manually call the ack callback
    ack({ status: 'ok' });
    }

function ConnectedSocket

ConnectedSocket: () => ParameterDecorator;

function MessageBody

MessageBody: {
(): ParameterDecorator;
(...pipes: any[]): ParameterDecorator;
(propertyKey: string, ...pipes: any[]): ParameterDecorator;
};
  • WebSockets message body parameter decorator.

  • WebSockets message body parameter decorator.

    Example:

    create(@MessageBody(new ValidationPipe()) createDto: CreateCatDto)

    Parameter pipes

    one or more pipes - either instances or classes - to apply to the bound parameter.

  • WebSockets message body parameter decorator. Extracts a property from the message payload object. May also apply pipes to the bound parameter.

    For example, extracting all params:

    findMany(@MessageBody() ids: string[])

    For example, extracting a single param:

    create(@MessageBody('data') createDto: { data: string })

    For example, extracting a single param with pipe:

    create(@MessageBody('data', new ValidationPipe()) createDto: { data: string })

    Parameter propertyKey

    name of single property to extract from the message payload

    Parameter pipes

    one or more pipes - either instances or classes - to apply to the bound parameter.

function SubscribeMessage

SubscribeMessage: <T = string>(message: T) => MethodDecorator;
  • Subscribes to messages that fulfils chosen pattern.

function WebSocketGateway

WebSocketGateway: {
(port?: number): ClassDecorator;
<T extends Record<string, any> = GatewayMetadata>(options?: T): ClassDecorator;
<T extends Record<string, any> = GatewayMetadata>(
port?: number,
options?: T
): ClassDecorator;
};
  • Decorator that marks a class as a Nest gateway that enables real-time, bidirectional and event-based communication between the browser and the server.

function WebSocketServer

WebSocketServer: () => PropertyDecorator;
  • Attaches native Web Socket Server to a given property.

Classes

class AbstractWsAdapter

abstract class AbstractWsAdapter<
TServer extends BaseWsInstance = any,
TClient extends BaseWsInstance = any,
TOptions = any
> implements WebSocketAdapter<TServer, TClient, TOptions> {}

    constructor

    constructor(appOrHttpServer?: any);

      property forceCloseConnections

      forceCloseConnections: boolean;

        property httpServer

        protected readonly httpServer: any;

          method bindClientConnect

          bindClientConnect: (server: TServer, callback: Function) => void;

            method bindClientDisconnect

            bindClientDisconnect: (client: TClient, callback: Function) => void;

              method bindMessageHandlers

              abstract bindMessageHandlers: (
              client: TClient,
              handlers: WsMessageHandler[],
              transform: (data: any) => Observable<any>
              ) => any;

                method close

                close: (server: TServer) => Promise<void>;

                  method create

                  abstract create: (port: number, options?: TOptions) => TServer;

                    method dispose

                    dispose: () => Promise<void>;

                      class BaseWsExceptionFilter

                      class BaseWsExceptionFilter<TError = any> implements WsExceptionFilter<TError> {}

                      constructor

                      constructor(options?: BaseWsExceptionFilterOptions);

                        property logger

                        protected static readonly logger: Logger;

                          property options

                          protected readonly options: BaseWsExceptionFilterOptions;

                            method catch

                            catch: (exception: TError, host: ArgumentsHost) => void;

                              method handleError

                              handleError: <TClient extends { emit: Function }>(
                              client: TClient,
                              exception: TError,
                              cause: ErrorPayload['cause']
                              ) => any;

                                method handleUnknownError

                                handleUnknownError: <TClient extends { emit: Function }>(
                                exception: TError,
                                client: TClient,
                                data: ErrorPayload['cause']
                                ) => void;

                                  method isExceptionObject

                                  isExceptionObject: (err: any) => err is Error;

                                    class WsException

                                    class WsException extends Error {}

                                      constructor

                                      constructor(error: string | object);

                                        method getError

                                        getError: () => string | object;

                                          method initMessage

                                          initMessage: () => void;

                                            Interfaces

                                            interface BaseWsInstance

                                            interface BaseWsInstance {}

                                              property close

                                              close: Function;

                                                property on

                                                on: (event: string, callback: Function) => void;

                                                  interface ErrorPayload

                                                  interface ErrorPayload<
                                                  Cause = {
                                                  pattern: string;
                                                  data: unknown;
                                                  }
                                                  > {}

                                                    property cause

                                                    cause?: Cause;
                                                    • Message that caused the exception.

                                                    property message

                                                    message: string;
                                                    • Error message.

                                                    property status

                                                    status: 'error';
                                                    • Error message identifier.

                                                    interface GatewayMetadata

                                                    interface GatewayMetadata {}
                                                    • External interface

                                                      See Also

                                                      • https://github.com/socketio/socket.io/blob/master/lib/index.ts

                                                    property adapter

                                                    adapter?: any;
                                                    • The adapter to use the in-memory adapter (https://github.com/socketio/socket.io-adapter)

                                                    property allowEIO3

                                                    allowEIO3?: boolean;
                                                    • Whether to enable compatibility with Socket.IO v2 clients false

                                                    property allowRequest

                                                    allowRequest?: (
                                                    req: any,
                                                    fn: (err: string | null | undefined, success: boolean) => void
                                                    ) => void;
                                                    • A function that receives a given handshake or upgrade request as its first parameter, and can decide whether to continue or not. The second argument is a function that needs to be called with the decided information: fn(err, success), where success is a boolean value where false means that the request is rejected, and err is an error code.

                                                    property allowUpgrades

                                                    allowUpgrades?: boolean;
                                                    • Whether to allow transport upgrades true

                                                    property connectTimeout

                                                    connectTimeout?: number;
                                                    • How many ms before a client without namespace is closed 45_000

                                                    property cookie

                                                    cookie?: any;
                                                    • Configuration of the cookie that contains the client sid to send as part of handshake response headers. This cookie might be used for sticky-session. Defaults to not sending any cookie. false

                                                    property cors

                                                    cors?: CorsOptions;
                                                    • The options that will be forwarded to the cors module

                                                    property destroyUpgrade

                                                    destroyUpgrade?: boolean;
                                                    • Destroy unhandled upgrade requests true

                                                    property destroyUpgradeTimeout

                                                    destroyUpgradeTimeout?: number;
                                                    • Milliseconds after which unhandled requests are ended 1_000

                                                    property httpCompression

                                                    httpCompression?: boolean | object;
                                                    • Parameters of the http compression for the polling transports (see zlib api docs). Set to false to disable. true

                                                    property initialPacket

                                                    initialPacket?: any;
                                                    • An optional packet which will be concatenated to the handshake packet emitted by Engine.IO.

                                                    property maxHttpBufferSize

                                                    maxHttpBufferSize?: number;
                                                    • How many bytes or characters a message can be, before closing the session (to avoid DoS). 1e6 (1 MB)

                                                    property namespace

                                                    namespace?: string | RegExp;
                                                    • The name of a namespace

                                                    property parser

                                                    parser?: any;
                                                    • The parser to use the default parser (https://github.com/socketio/socket.io-parser)

                                                    property path

                                                    path?: string;
                                                    • Name of the path to capture "/socket.io"

                                                    property perMessageDeflate

                                                    perMessageDeflate?: boolean | object;
                                                    • Parameters of the WebSocket permessage-deflate extension (see ws module api docs). Set to false to disable. false

                                                    property pingInterval

                                                    pingInterval?: number;
                                                    • How many ms before sending a new ping packet 25_000

                                                    property pingTimeout

                                                    pingTimeout?: number;
                                                    • How many ms without a pong packet to consider the connection closed 20_000

                                                    property serveClient

                                                    serveClient?: boolean;
                                                    • Whether to serve the client files true

                                                    property transports

                                                    transports?: Array<'polling' | 'websocket'>;
                                                    • The low-level transports that are enabled ["polling", "websocket"]

                                                    property upgradeTimeout

                                                    upgradeTimeout?: number;
                                                    • How many ms before an uncompleted transport upgrade is cancelled 10_000

                                                    property wsEngine

                                                    wsEngine?: string;
                                                    • What WebSocket server implementation to use. Specified module must conform to the ws interface (see ws module api docs). Default value is ws. An alternative c++ addon is also available by installing uws module.

                                                    interface MessageMappingProperties

                                                    interface MessageMappingProperties {}

                                                      property callback

                                                      callback: (...args: any[]) => Observable<any> | Promise<any>;

                                                        property isAckHandledManually

                                                        isAckHandledManually: boolean;

                                                          property message

                                                          message: any;

                                                            property methodName

                                                            methodName: string;

                                                              interface OnGatewayConnection

                                                              interface OnGatewayConnection<T = any> {}

                                                              method handleConnection

                                                              handleConnection: (client: T, ...args: any[]) => any;

                                                                interface OnGatewayDisconnect

                                                                interface OnGatewayDisconnect<T = any> {}

                                                                method handleDisconnect

                                                                handleDisconnect: (client: T) => any;

                                                                  interface OnGatewayInit

                                                                  interface OnGatewayInit<T = any> {}

                                                                  method afterInit

                                                                  afterInit: (server: T) => any;

                                                                    interface ServerAndEventStreamsHost

                                                                    interface ServerAndEventStreamsHost<T = any> {}

                                                                    property connection

                                                                    connection: Subject<any>;

                                                                      property disconnect

                                                                      disconnect: Subject<any>;

                                                                        property init

                                                                        init: ReplaySubject<T>;

                                                                          property server

                                                                          server: T;

                                                                            interface WebSocketServerOptions

                                                                            interface WebSocketServerOptions {}

                                                                            property namespace

                                                                            namespace: string;

                                                                              property port

                                                                              port: number;

                                                                                interface WsResponse

                                                                                interface WsResponse<T = any> {}

                                                                                property data

                                                                                data: T;

                                                                                  property event

                                                                                  event: string;

                                                                                    Package Files (18)

                                                                                    Dependencies (3)

                                                                                    Dev Dependencies (2)

                                                                                    Peer Dependencies (5)

                                                                                    Badge

                                                                                    To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                                    You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@nestjs/websockets.

                                                                                    • Markdown
                                                                                      [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@nestjs/websockets)
                                                                                    • HTML
                                                                                      <a href="https://www.jsdocs.io/package/@nestjs/websockets"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>