@nestjs/websockets
Version:
WebSockets for NestJS: gateways with message handlers, guards, pipes and interceptors, on Socket.IO or ws.
36 lines (35 loc) • 1.35 kB
JavaScript
import { WsParamtype } from '../enums/ws-paramtype.enum.js';
import { isFunction, isNil, isObject } from '@nestjs/common/internal';
/**
* A key picks a property of an object payload. Of an array, a Buffer or a
* primitive the client sent instead, it picks only an own property (an
* element, a length), not a prototype member: `Buffer#parent` exposes memory
* shared with other requests, and a built-in function such as
* `Array.prototype.values` passes for a DTO without required properties.
* Objects keep resolving inherited properties, as a custom message parser may
* build class instances.
*/
const getPayloadProperty = (payload, key) => (isObject(payload) &&
!Array.isArray(payload) &&
!ArrayBuffer.isView(payload)) ||
(!isNil(payload) && Object.hasOwn(Object(payload), key))
? payload[key]
: undefined;
export class WsParamsFactory {
exchangeKeyForValue(type, data, args) {
if (!args) {
return null;
}
switch (type) {
case WsParamtype.SOCKET:
return args[0];
case WsParamtype.PAYLOAD:
return data ? getPayloadProperty(args[1], data) : args[1];
case WsParamtype.ACK: {
return args.find(arg => isFunction(arg));
}
default:
return null;
}
}
}