@nestjs/websockets
Version:
WebSockets for NestJS: gateways with message handlers, guards, pipes and interceptors, on Socket.IO or ws.
179 lines (178 loc) • 9.34 kB
JavaScript
import { CUSTOM_ROUTE_ARGS_METADATA, isEmptyArray, PARAMTYPES_METADATA, } from '@nestjs/common/internal';
import { ContextUtils, FORBIDDEN_MESSAGE, HandlerMetadataStorage, STATIC_CONTEXT, } from '@nestjs/core/internal';
import { MESSAGE_METADATA, PARAM_ARGS_METADATA } from '../constants.js';
import { WsException } from '../errors/ws-exception.js';
import { WsParamsFactory } from '../factories/ws-params-factory.js';
import { DEFAULT_CALLBACK_METADATA } from './ws-metadata-constants.js';
const isThenable = (value) => value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof value.then === 'function';
export class WsContextCreator {
wsProxy;
exceptionFiltersContext;
pipesContextCreator;
pipesConsumer;
guardsContextCreator;
guardsConsumer;
interceptorsContextCreator;
interceptorsConsumer;
contextUtils = new ContextUtils();
wsParamsFactory = new WsParamsFactory();
handlerMetadataStorage = new HandlerMetadataStorage();
constructor(wsProxy, exceptionFiltersContext, pipesContextCreator, pipesConsumer, guardsContextCreator, guardsConsumer, interceptorsContextCreator, interceptorsConsumer) {
this.wsProxy = wsProxy;
this.exceptionFiltersContext = exceptionFiltersContext;
this.pipesContextCreator = pipesContextCreator;
this.pipesConsumer = pipesConsumer;
this.guardsContextCreator = guardsContextCreator;
this.guardsConsumer = guardsConsumer;
this.interceptorsContextCreator = interceptorsContextCreator;
this.interceptorsConsumer = interceptorsConsumer;
}
create(instance, callback, moduleKey, methodName, contextId = STATIC_CONTEXT, inquirerId) {
const contextType = 'ws';
const { argsLength, paramtypes, getParamsMetadata } = this.getMetadata(instance, methodName, contextType);
const exceptionHandler = this.exceptionFiltersContext.create(instance, callback, moduleKey, contextId, inquirerId);
const pipes = this.pipesContextCreator.create(instance, callback, moduleKey, contextId, inquirerId);
const guards = this.guardsContextCreator.create(instance, callback, moduleKey, contextId, inquirerId);
const interceptors = this.interceptorsContextCreator.create(instance, callback, moduleKey, contextId, inquirerId);
const paramsMetadata = getParamsMetadata(moduleKey, contextId, inquirerId);
const paramsOptions = paramsMetadata
? this.contextUtils.mergeParamsMetatypes(paramsMetadata, paramtypes)
: [];
// Optional call, as an older "@nestjs/core" may not implement it
this.contextUtils.warnOnMissingParamtypes?.(instance, methodName, paramtypes, pipes, paramsOptions);
const fnApplyPipes = this.createPipesFn(pipes, paramsOptions);
const fnCanActivate = this.createGuardsFn(guards, instance, callback, contextType);
const handler = (initialArgs, args) => async () => {
if (fnApplyPipes) {
const pendingPipes = fnApplyPipes(initialArgs, ...args);
pendingPipes && (await pendingPipes);
return callback.apply(instance, initialArgs);
}
return callback.apply(instance, args);
};
const targetPattern = this.reflectCallbackPattern(callback);
return this.wsProxy.create(async (...args) => {
// The pattern is already appended by `WsProxy` before this callback runs,
// so it is the last element of `args` at this point.
const initialArgs = this.contextUtils.createNullArray(argsLength);
fnCanActivate && (await fnCanActivate(args));
return this.interceptorsConsumer.intercept(interceptors, args, instance, callback, handler(initialArgs, args), contextType);
}, exceptionHandler, targetPattern);
}
reflectCallbackParamtypes(instance, callback) {
return Reflect.getMetadata(PARAMTYPES_METADATA, instance, callback.name);
}
reflectCallbackPattern(callback) {
return Reflect.getMetadata(MESSAGE_METADATA, callback);
}
createGuardsFn(guards, instance, callback, contextType) {
const canActivateFn = async (args) => {
const canActivate = await this.guardsConsumer.tryActivate(guards, args, instance, callback, contextType);
if (!canActivate) {
throw new WsException(FORBIDDEN_MESSAGE);
}
};
return guards.length ? canActivateFn : null;
}
getMetadata(instance, methodName, contextType) {
const cacheMetadata = this.handlerMetadataStorage.get(instance, methodName);
if (cacheMetadata) {
return cacheMetadata;
}
const metadata = this.contextUtils.reflectCallbackMetadata(instance, methodName, PARAM_ARGS_METADATA) || DEFAULT_CALLBACK_METADATA;
const keys = Object.keys(metadata);
const argsLength = this.contextUtils.getArgumentsLength(keys, metadata);
const paramtypes = this.contextUtils.reflectCallbackParamtypes(instance, methodName);
const contextFactory = this.contextUtils.getContextFactory(contextType, instance, instance[methodName]);
const getParamsMetadata = (moduleKey, contextId = STATIC_CONTEXT, inquirerId) => this.exchangeKeysForValues(keys, metadata, moduleKey, this.wsParamsFactory, contextFactory, contextId, inquirerId);
const handlerMetadata = {
argsLength,
paramtypes,
getParamsMetadata,
};
this.handlerMetadataStorage.set(instance, methodName, handlerMetadata);
return handlerMetadata;
}
exchangeKeysForValues(keys, metadata, moduleContext, paramsFactory, contextFactory, contextId = STATIC_CONTEXT, inquirerId) {
this.pipesContextCreator.setModuleContext(moduleContext);
return keys.map(key => {
const { index, data, pipes: pipesCollection, schema } = metadata[key];
const pipes = this.pipesContextCreator.createConcreteContext(pipesCollection, contextId, inquirerId);
const type = this.contextUtils.mapParamType(key);
if (key.includes(CUSTOM_ROUTE_ARGS_METADATA)) {
const { factory } = metadata[key];
const customExtractValue = this.contextUtils.getCustomFactory(factory, data, contextFactory);
return {
index,
extractValue: customExtractValue,
type,
data,
pipes,
schema,
};
}
const numericType = Number(type);
const extractValue = (...args) => paramsFactory.exchangeKeyForValue(numericType, data, args);
return { index, extractValue, type: numericType, data, pipes, schema };
});
}
createPipesFn(pipes, paramsOptions) {
if (!paramsOptions.length) {
return null;
}
// Which pipes a param runs through is fixed for the handler, so it is
// worked out once here rather than on every call.
const params = paramsOptions.map(({ index, extractValue, type, data, metatype, pipes: paramPipes, schema, }) => ({
index,
extractValue,
metadata: { metatype, type, data, schema },
pipes: pipes.concat(paramPipes),
}));
const applyPipes = async (args, param, value) => {
args[param.index] = await this.getParamValue(value, param.metadata, param.pipes);
};
const settle = async (pending) => {
try {
await Promise.all(pending);
}
catch (err) {
// The pipes of the other parameters are still running. Answering now
// would free the message's slot (see "maxConcurrentMessages" of the
// adapters) while their work goes on, so a client could have any
// number of them running by sending messages that fail fast.
await Promise.allSettled(pending);
throw err;
}
};
return (args, ...extractArgs) => {
// A value no pipe runs on is final once extracted and needs no promise,
// unless it is a thenable, which getParamValue() has always settled.
// The rest, and any extractor that throws, go through one
// Promise.all() in param order, as before.
let pending;
for (let i = 0; i < params.length; i++) {
const param = params[i];
try {
const value = param.extractValue(...extractArgs);
if (param.pipes.length > 0 || isThenable(value)) {
(pending ??= []).push(applyPipes(args, param, value));
}
else {
args[param.index] = value;
}
}
catch (err) {
(pending ??= []).push(Promise.reject(err));
}
}
return pending && settle(pending);
};
}
async getParamValue(value, metadata, pipes) {
return isEmptyArray(pipes)
? value
: this.pipesConsumer.apply(value, metadata, pipes);
}
}