@nestjs/websockets
Version:
Nest - modern, fast, powerful node.js web framework (@websockets)
57 lines (56 loc) • 2.28 kB
JavaScript
import { GATEWAY_SERVER_METADATA, MESSAGE_MAPPING_METADATA, MESSAGE_METADATA, PARAM_ARGS_METADATA, } from './constants.js';
import { WsParamtype } from './enums/ws-paramtype.enum.js';
import { isFunction, isUndefined } from '@nestjs/common/internal';
import { ContextUtils } from '@nestjs/core/internal';
export class GatewayMetadataExplorer {
metadataScanner;
contextUtils = new ContextUtils();
constructor(metadataScanner) {
this.metadataScanner = metadataScanner;
}
explore(instance) {
const instancePrototype = Object.getPrototypeOf(instance);
return this.metadataScanner
.getAllMethodNames(instancePrototype)
.map(method => this.exploreMethodMetadata(instancePrototype, method))
.filter(metadata => metadata);
}
exploreMethodMetadata(instancePrototype, methodName) {
const callback = instancePrototype[methodName];
const isMessageMapping = Reflect.getMetadata(MESSAGE_MAPPING_METADATA, callback);
if (isUndefined(isMessageMapping)) {
return null;
}
const message = Reflect.getMetadata(MESSAGE_METADATA, callback);
const isAckHandledManually = this.hasAckDecorator(instancePrototype, methodName);
return {
callback,
message,
methodName,
isAckHandledManually,
};
}
hasAckDecorator(instancePrototype, methodName) {
const paramsMetadata = Reflect.getMetadata(PARAM_ARGS_METADATA, instancePrototype.constructor, methodName);
if (!paramsMetadata) {
return false;
}
const metadataKeys = Object.keys(paramsMetadata);
return metadataKeys.some(key => {
const type = this.contextUtils.mapParamType(key);
return Number(type) === WsParamtype.ACK;
});
}
*scanForServerHooks(instance) {
for (const propertyKey in instance) {
if (isFunction(instance[propertyKey])) {
continue;
}
const property = String(propertyKey);
const isServer = Reflect.getMetadata(GATEWAY_SERVER_METADATA, instance, property);
if (!isUndefined(isServer)) {
yield property;
}
}
}
}