@nestjs/core
Version:
The core of NestJS, a TypeScript framework for Node.js backends: modules, dependency injection and the request pipeline, on Express, Fastify or node:http.
73 lines (72 loc) • 3.2 kB
JavaScript
import { iterate } from 'iterare';
import { getClassRef } from '../helpers/class-ref-registry.js';
import { ContextCreator } from '../helpers/context-creator.js';
import { STATIC_CONTEXT } from '../injector/constants.js';
import { FILTER_CATCH_EXCEPTIONS, isEmpty, isFunction, } from '@nestjs/common/internal';
export class BaseExceptionFilterContext extends ContextCreator {
container;
moduleContext;
constructor(container) {
super();
this.container = container;
}
createConcreteContext(metadata, contextId = STATIC_CONTEXT, inquirerId) {
if (isEmpty(metadata)) {
return [];
}
return iterate(metadata)
.filter(instance => instance && (isFunction(instance.catch) || isFunction(instance)))
.map(filter => this.getFilterInstance(filter, contextId, inquirerId))
.filter(item => !!item)
.map(instance => ({
func: instance.catch.bind(instance),
exceptionMetatypes: this.reflectCatchExceptions(instance),
}))
.toArray();
}
getFilterInstance(filter, contextId = STATIC_CONTEXT, inquirerId) {
if (!isFunction(filter)) {
return filter;
}
const instanceWrapper = this.getInstanceByMetatype(filter);
if (!instanceWrapper) {
return this.pickEnhancer(filter, null, 'catch');
}
const instanceHost = instanceWrapper.getInstanceByContextId(this.getContextId(contextId, instanceWrapper), inquirerId);
if (instanceHost && !this.isInstantiated(instanceWrapper, instanceHost)) {
return null;
}
return this.pickEnhancer(filter, instanceHost && instanceHost.instance, 'catch');
}
/**
* A filter class that has not been instantiated in a context (or for an
* inquirer) is represented there by an object created from its prototype,
* e.g. a request-scoped filter of a controller that failed to resolve for
* the request. Its "catch()" would run without its constructor having been
* called, i.e. without its dependencies.
*/
isInstantiated(instanceWrapper, instanceHost) {
return instanceWrapper.isNotMetatype || !!instanceHost.isConstructorCalled;
}
getInstanceByMetatype(metatype) {
if (!this.moduleContext) {
return;
}
const collection = this.container.getModules();
const moduleRef = collection.get(this.moduleContext);
if (!moduleRef) {
return;
}
return moduleRef.injectables.get(metatype);
}
reflectCatchExceptions(instance) {
// `@Catch()` also stores the types on the prototype of the filter class,
// because the "constructor" of that prototype may name another class (see
// `getClassRef`), and a filter the application instantiated itself is not
// a registered class. The class lookup serves filters that an older
// `@Catch()` decorated.
return (Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, Object.getPrototypeOf(instance)) ??
Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, getClassRef(instance)) ??
[]);
}
}