UNPKG

@nestjs/microservices

Version:

Microservices for NestJS: message and event handlers over Kafka, RabbitMQ, NATS, Redis, MQTT, gRPC or TCP.

55 lines (54 loc) • 2.39 kB
import { iterate } from 'iterare'; import { RpcExceptionsHandler } from '../exceptions/rpc-exceptions-handler.js'; import { EXCEPTION_FILTERS_METADATA, isEmptyArray, } from '@nestjs/common/internal'; import { BaseExceptionFilterContext, STATIC_CONTEXT, } from '@nestjs/core/internal'; /** * 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. * Its "catch()" would run without its constructor having been called, i.e. * without its dependencies. Filters given as value or factory providers have * no constructor to call. * * Checked here rather than through the "isInstantiated()" method of * "BaseExceptionFilterContext", which a supported "@nestjs/core" may not have. */ function isInstantiated(wrapper, host) { return wrapper.isNotMetatype || !!host.isConstructorCalled; } /** * @publicApi */ export class ExceptionFiltersContext extends BaseExceptionFilterContext { config; constructor(container, config) { super(container); this.config = config; } create(instance, callback, module, contextId = STATIC_CONTEXT, inquirerId) { this.moduleContext = module; const exceptionHandler = new RpcExceptionsHandler(); const filters = this.createContext(instance, callback, EXCEPTION_FILTERS_METADATA, contextId, inquirerId); if (isEmptyArray(filters)) { return exceptionHandler; } exceptionHandler.setCustomFilters(filters.reverse()); return exceptionHandler; } getGlobalMetadata(contextId = STATIC_CONTEXT, inquirerId) { const globalFilters = this.config.getGlobalFilters(); if (contextId === STATIC_CONTEXT && !inquirerId) { return globalFilters; } const scopedFilterWrappers = this.config.getGlobalRequestFilters(); const scopedFilters = iterate(scopedFilterWrappers) .map(wrapper => ({ wrapper, host: wrapper.getInstanceByContextId(this.getContextId(contextId, wrapper), inquirerId), })) // e.g. a request-scoped filter that the message did not instantiate .filter(({ wrapper, host }) => !!host && isInstantiated(wrapper, host)) .map(({ host }) => host.instance) .toArray(); return globalFilters.concat(scopedFilters); } }