@nestjs/websockets
- Version 12.0.1
- Published
- 88.6 kB
- 3 dependencies
- MIT license
Install
npm i @nestjs/websocketsyarn add @nestjs/websocketspnpm add @nestjs/websocketsOverview
Nest - modern, fast, powerful node.js web framework (@websockets)
Index
Functions
Classes
Interfaces
Functions
function Ack
Ack: () => ParameterDecorator;WebSockets
ackparameter decorator. Extracts theackcallback function from the arguments of a ws event.This decorator signals to the framework that the
ackcallback 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 callbackack({ status: 'ok' });}
function ConnectedSocket
ConnectedSocket: () => ParameterDecorator;function MessageBody
MessageBody: { (): ParameterDecorator; (...pipes: any[]): ParameterDecorator; (propertyKey: string, ...pipes: any[]): ParameterDecorator; (propertyKey: string, options: ParameterDecoratorOptions): ParameterDecorator; (options: ParameterDecoratorOptions): 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.
WebSockets message body parameter decorator. Extracts a property from the message payload object with additional options.
For example, extracting a single param with schema:
create(@MessageBody('data', { schema: z.string() }) data: string)Parameter propertyKey
name of single property to extract from the message payload
Parameter options
options object containing additional configuration for the decorator, such as pipes and schema
WebSockets message body parameter decorator.
For example, passing schema as options:
create(@MessageBody({ schema: z.object({ data: z.string() }) }) body)Parameter options
options object containing additional configuration for the decorator, such as pipes and schema
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 emitMessage
protected emitMessage: <TClient extends { emit?: Function; send?: Function }>( client: TClient, event: string, payload: unknown) => void;Sends an error message to the client. Supports both Socket.IO clients (which use
emit) and native WebSocket clients (which usesend).Native WebSocket clients (e.g. from the
wspackage) inherit from EventEmitter and therefore also have anemitmethod, but that method only dispatches events locally. To distinguish native WebSocket clients from Socket.IO clients, we check for a numericreadyStateproperty (part of the WebSocket specification) before falling back toemit.
method handleError
handleError: <TClient extends { emit?: Function; send?: Function }>( client: TClient, exception: TError, cause: ErrorPayload['cause']) => void;method handleUnknownError
handleUnknownError: <TClient extends { emit?: Function; send?: 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 {}interface ErrorPayload
interface ErrorPayload< Cause = { pattern: string; data: unknown; }> {}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, reason?: string) => 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 {}interface WsResponse
interface WsResponse<T = any> {}Package Files (18)
- adapters/ws-adapter.d.ts
- decorators/ack.decorator.d.ts
- decorators/connected-socket.decorator.d.ts
- decorators/gateway-server.decorator.d.ts
- decorators/message-body.decorator.d.ts
- decorators/socket-gateway.decorator.d.ts
- decorators/subscribe-message.decorator.d.ts
- errors/ws-exception.d.ts
- exceptions/base-ws-exception-filter.d.ts
- gateway-metadata-explorer.d.ts
- index.d.ts
- interfaces/gateway-metadata.interface.d.ts
- interfaces/hooks/on-gateway-connection.interface.d.ts
- interfaces/hooks/on-gateway-disconnect.interface.d.ts
- interfaces/hooks/on-gateway-init.interface.d.ts
- interfaces/server-and-event-streams-host.interface.d.ts
- interfaces/web-socket-server.interface.d.ts
- interfaces/ws-response.interface.d.ts
Dependencies (3)
Dev Dependencies (2)
Peer Dependencies (5)
Badge
To add a badge like this oneto 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[](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>
- Updated .
Package analyzed in 3649 ms. - Missing or incorrect documentation? Open an issue for this package.
