UNPKG

@nestjs/websockets

Version:

WebSockets for NestJS: gateways with message handlers, guards, pipes and interceptors, on Socket.IO or ws.

155 lines (154 loc) • 5.74 kB
import { IntrinsicException, Logger, } from '@nestjs/common'; import { WsException } from '../errors/ws-exception.js'; import { isFunction, isNumber, isObject } from '@nestjs/common/internal'; import { MESSAGES } from '@nestjs/core/internal'; /** * Whether a value holds binary data (a Buffer, an ArrayBuffer or a view of * one, or a Blob) anywhere in it. A loop with a record of what it has seen, * not recursion: the value comes from the client, which decides how deep it * is nested, and may refer to an object more than once. */ function holdsBinary(value) { const pending = [value]; const seen = new Set(); while (pending.length > 0) { const current = pending.pop(); if (typeof current !== 'object' || current === null) { continue; } if (current instanceof ArrayBuffer || ArrayBuffer.isView(current) || (typeof Blob !== 'undefined' && current instanceof Blob)) { return true; } if (seen.has(current)) { continue; } seen.add(current); for (const item of Object.values(current)) { pending.push(item); } } return false; } /** * Leaves the data out when it holds binary data, so that an error reply does * not send the client's binary data back to it. */ const defaultCauseFactory = (pattern, data) => holdsBinary(data) ? { pattern } : { pattern, data }; /** * @publicApi */ export class BaseWsExceptionFilter { options; static logger = new Logger('WsExceptionsHandler'); constructor(options = {}) { this.options = options; this.options = { ...this.options, includeCause: this.options.includeCause ?? true, causeFactory: this.options.causeFactory ?? defaultCauseFactory, }; } catch(exception, host) { const client = host.switchToWs().getClient(); const pattern = host.switchToWs().getPattern(); const data = host.switchToWs().getData(); this.handleError(client, exception, { pattern, data, }); } handleError(client, exception, cause) { if (!(exception instanceof WsException)) { return this.handleUnknownError(exception, client, cause); } const status = 'error'; const result = exception.getError(); // An Error, as in `new WsException(err)`, would be sent with its // enumerable properties, e.g. the request config of an HTTP client error if (result instanceof Error) { return this.handleUnknownError(result, client, cause); } if (isObject(result)) { return this.emitMessage(client, 'exception', result); } const payload = { status, message: result, }; if (this.options?.includeCause && cause) { payload.cause = this.options.causeFactory(cause.pattern, cause.data); } this.emitErrorPayload(client, payload); } handleUnknownError(exception, client, data) { const status = 'error'; const payload = { status, message: MESSAGES.UNKNOWN_EXCEPTION_MESSAGE, }; if (this.options?.includeCause && data) { payload.cause = this.options.causeFactory(data.pattern, data.data); } // Logged first, so that a reply that cannot be sent never hides it if (!(exception instanceof IntrinsicException)) { const logger = BaseWsExceptionFilter.logger; logger.error(exception); } this.emitErrorPayload(client, payload); } isExceptionObject(err) { return isObject(err) && !!err.message; } /** * Sends an error message to the client. Supports both Socket.IO clients * (which use `emit`) and native WebSocket clients (which use `send`). * * Native WebSocket clients (e.g. from the `ws` package) inherit from * EventEmitter and therefore also have an `emit` method, but that method * only dispatches events locally. To distinguish native WebSocket clients * from Socket.IO clients, we check for a numeric `readyState` property * (part of the WebSocket specification) before falling back to `emit`. */ emitMessage(client, event, payload) { if (this.isNativeWebSocket(client)) { client.send(JSON.stringify({ event, data: payload, })); } else if (isFunction(client.emit)) { client.emit(event, payload); } } /** * Sends the error payload, and sends it again without the "cause" when that * fails. The cause echoes the client's message, which `JSON.parse` accepts * at any depth, while `JSON.stringify` and the Socket.IO encoder overflow * the stack on it. */ emitErrorPayload(client, payload) { try { this.emitMessage(client, 'exception', payload); } catch (err) { // Without a cause, the payload holds nothing the client sent if (!('cause' in payload)) { throw err; } this.emitMessage(client, 'exception', { status: payload.status, message: payload.message, }); } } /** * Determines whether the given client is a native WebSocket (e.g. from the * `ws` package) as opposed to a Socket.IO socket. Native WebSocket objects * expose a numeric `readyState` property per the WebSocket specification. */ isNativeWebSocket(client) { return isNumber(client.readyState) && isFunction(client.send); } }