UNPKG

@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.

276 lines (275 loc) • 14.1 kB
import { Logger } from '@nestjs/common'; import { InvalidMiddlewareException } from '../errors/exceptions/invalid-middleware.exception.js'; import { RuntimeException } from '../errors/exceptions/runtime.exception.js'; import { ContextIdFactory } from '../helpers/context-id-factory.js'; import { ExecutionContextHost } from '../helpers/execution-context-host.js'; import { STATIC_CONTEXT } from '../injector/constants.js'; import { REQUEST_CONTEXT_ID } from '../router/request/request-constants.js'; import { RouterExceptionFilters } from '../router/router-exception-filters.js'; import { RouterProxy } from '../router/router-proxy.js'; import { isRequestMethodAll } from '../router/utils/index.js'; import { MiddlewareBuilder } from './builder.js'; import { MiddlewareResolver } from './resolver.js'; import { RouteInfoPathExtractor } from './route-info-path-extractor.js'; import { RoutesMapper } from './routes-mapper.js'; import { RequestMethod } from '@nestjs/common'; import { EXCEPTION_FILTERS_METADATA, isFunction, isUndefined, } from '@nestjs/common/internal'; export class MiddlewareModule { routerProxy = new RouterProxy(); logger = new Logger(MiddlewareModule.name); // Middleware already checked for filter classes (see // "warnAboutFilterClasses()") checkedFilterBindings = new WeakSet(); injector; routerExceptionFilter; routesMapper; resolver; container; httpAdapter; graphInspector; appOptions; routeInfoPathExtractor; async register(middlewareContainer, container, config, injector, httpAdapter, graphInspector, options) { this.appOptions = options; const appRef = container.getHttpAdapterRef(); this.routerExceptionFilter = new RouterExceptionFilters(container, config, appRef); this.routesMapper = new RoutesMapper(container, config); this.resolver = new MiddlewareResolver(middlewareContainer, injector); this.routeInfoPathExtractor = new RouteInfoPathExtractor(config, () => this.routesMapper.mapControllersToRouteInfo()); this.injector = injector; this.container = container; this.httpAdapter = httpAdapter; this.graphInspector = graphInspector; const modules = container.getModules(); await this.resolveMiddleware(middlewareContainer, modules); } async resolveMiddleware(middlewareContainer, modules) { const moduleEntries = [...modules.entries()]; const loadMiddlewareConfiguration = async ([moduleName, moduleRef]) => { await this.loadConfiguration(middlewareContainer, moduleRef, moduleName); await this.resolver.resolveInstances(moduleRef, moduleName); }; await Promise.all(moduleEntries.map(loadMiddlewareConfiguration)); } async loadConfiguration(middlewareContainer, moduleRef, moduleKey) { const { instance } = moduleRef; if (!instance.configure) { return; } // The modules' "configure()" methods run concurrently, and // "registerMiddleware()" mounts the middleware of modules at the same // distance in the order of their configurations: a module whose // "configure()" awaits must not end up behind the modules after it middlewareContainer.reserveConfig(moduleKey); const middlewareBuilder = new MiddlewareBuilder(this.routesMapper, this.httpAdapter, this.routeInfoPathExtractor); try { await instance.configure(middlewareBuilder); } catch (err) { if (!this.appOptions.preview) { throw err; } const warningMessage = `Warning! "${moduleRef.name}" module exposes a "configure" method that throws an exception in the preview mode` + ` (possibly due to missing dependencies). Note: you can ignore this message, just be aware that some of those conditional middlewares will not be reflected in your graph.`; this.logger.warn(warningMessage); } if (!(middlewareBuilder instanceof MiddlewareBuilder)) { return; } const config = middlewareBuilder.build(); middlewareContainer.insertConfig(config, moduleKey); } async registerMiddleware(middlewareContainer, applicationRef) { const configs = middlewareContainer.getConfigurations(); const registerAllConfigs = async (moduleKey, middlewareConfig) => { for (const config of middlewareConfig) { await this.registerMiddlewareConfig(middlewareContainer, config, moduleKey, applicationRef); } }; const entriesSortedByDistance = [...configs.entries()].sort(([moduleA], [moduleB]) => { const moduleARef = this.container.getModuleByKey(moduleA); const moduleBRef = this.container.getModuleByKey(moduleB); const isModuleAGlobal = moduleARef.distance === Number.MAX_VALUE; const isModuleBGlobal = moduleBRef.distance === Number.MAX_VALUE; if (isModuleAGlobal && isModuleBGlobal) { return 0; } if (isModuleAGlobal) { return -1; } if (isModuleBGlobal) { return 1; } return moduleARef.distance - moduleBRef.distance; }); for (const [moduleRef, moduleConfigurations] of entriesSortedByDistance) { await registerAllConfigs(moduleRef, [...moduleConfigurations]); } } async registerMiddlewareConfig(middlewareContainer, config, moduleKey, applicationRef) { const { forRoutes } = config; // Shared by the routes of this configuration that differ only in their // version (see `getHandledRequests()`) const handledRequestsByRoute = new Map(); for (const routeInfo of forRoutes) { await this.registerRouteMiddleware(middlewareContainer, routeInfo, config, moduleKey, applicationRef, handledRequestsByRoute); } } async registerRouteMiddleware(middlewareContainer, routeInfo, config, moduleKey, applicationRef, handledRequestsByRoute = new Map()) { const middlewareCollection = [].concat(config.middleware); const moduleRef = this.container.getModuleByKey(moduleKey); for (const metatype of middlewareCollection) { const collection = middlewareContainer.getMiddlewareCollection(moduleKey); const instanceWrapper = collection.get(metatype); if (isUndefined(instanceWrapper)) { throw new RuntimeException(); } this.graphInspector.insertClassNode(moduleRef, instanceWrapper, 'middleware'); const middlewareDefinition = { type: 'middleware', methodName: 'use', className: instanceWrapper.name, classNodeId: instanceWrapper.id, metadata: { key: routeInfo.path, path: routeInfo.path, requestMethod: RequestMethod[routeInfo.method] ?? 'ALL', version: routeInfo.version, }, }; this.graphInspector.insertEntrypointDefinition(middlewareDefinition, instanceWrapper.id); await this.bindHandler(instanceWrapper, applicationRef, routeInfo, moduleRef, collection, this.getHandledRequests(handledRequestsByRoute, metatype, routeInfo)); } } async bindHandler(wrapper, applicationRef, routeInfo, moduleRef, collection, handledRequests) { const { instance, metatype } = wrapper; if (isUndefined(instance?.use)) { throw new InvalidMiddlewareException(metatype.name); } this.warnAboutFilterClasses(metatype, instance.use); // A transient middleware is its own inquirer, and the injector creates // such an instance only for a context: it is resolved per request, like a // request-scoped one (its static instance is never constructed) const isStatic = wrapper.isDependencyTreeStatic() && !wrapper.isTransient; if (isStatic) { const proxy = await this.createProxy(instance); return this.registerHandler(applicationRef, routeInfo, proxy, handledRequests); } const isTreeDurable = wrapper.isDependencyTreeDurable(); // Kept per route, not per "use" function: middleware that inherits it // from a base class can declare different filters let exceptionsHandler; await this.registerHandler(applicationRef, routeInfo, async (req, res, next) => { try { const contextId = this.getContextId(req, isTreeDurable); const contextInstance = await this.injector.loadPerContext(instance, moduleRef, collection, contextId); const proxy = await this.createProxy(contextInstance, contextId); return proxy(req, res, next); } catch (err) { exceptionsHandler ??= this.routerExceptionFilter.create(instance, instance.use, undefined); const host = new ExecutionContextHost([req, res, next]); exceptionsHandler.next(err, host); } }, handledRequests); } /** * Exception filters bound to a middleware with @UseFilters() apply only * when they are instances: a filter class has no module to be resolved in * for a middleware, so it is left out. Warns once per middleware. */ warnAboutFilterClasses(metatype, use) { if (!metatype || this.checkedFilterBindings.has(metatype)) { return; } this.checkedFilterBindings.add(metatype); const filterClasses = [ ...(Reflect.getMetadata(EXCEPTION_FILTERS_METADATA, metatype) ?? []), ...(Reflect.getMetadata(EXCEPTION_FILTERS_METADATA, use) ?? []), ].filter(filter => isFunction(filter) && !isFunction(filter.catch)); if (filterClasses.length === 0) { return; } const names = [ ...new Set(filterClasses.map(filter => `"${filter.name}"`)), ].join(', '); this.logger.warn(`The exception filter classes ${names} bound to the "${metatype.name}" middleware with @UseFilters() are not applied to it: a middleware only applies filter instances, such as @UseFilters(new ${filterClasses[0].name}()). Pass instances, or register the filters globally.`); } /** * Returns the requests the middleware already ran for on the route. Routes * that differ only in their version (e.g. a controller with the versions * `['1', '2']`) share it: unless the version is part of the path (URI * versioning), they are mounted on the same path, and the middleware would * run once for each of them. */ getHandledRequests(handledRequestsByRoute, middleware, { path, method }) { let byRoute = handledRequestsByRoute.get(middleware); if (!byRoute) { byRoute = new Map(); handledRequestsByRoute.set(middleware, byRoute); } const key = `${method}:${path}`; let handledRequests = byRoute.get(key); if (!handledRequests) { handledRequests = new WeakSet(); byRoute.set(key, handledRequests); } return handledRequests; } async createProxy(instance, contextId = STATIC_CONTEXT) { const exceptionsHandler = this.routerExceptionFilter.create(instance, instance.use, undefined, contextId); const middleware = instance.use.bind(instance); return this.routerProxy.createProxy(middleware, exceptionsHandler); } async registerHandler(applicationRef, routeInfo, proxy, handledRequests) { const { method } = routeInfo; const paths = this.routeInfoPathExtractor.extractPathsFrom(routeInfo); const isMethodAll = isRequestMethodAll(method); const requestMethod = RequestMethod[method]; const router = await applicationRef.createMiddlewareFactory(method); const middlewareFunction = isMethodAll ? proxy : (req, res, next) => { const actualRequestMethod = applicationRef.getRequestMethod?.(req); if (actualRequestMethod === requestMethod || (actualRequestMethod === RequestMethod[RequestMethod.HEAD] && requestMethod === RequestMethod[RequestMethod.GET])) { return proxy(req, res, next); } return next(); }; // The paths may overlap (e.g. "/" and "/api/*" when the root path is // excluded from the global prefix): the middleware runs for the first of // them that matches a request, and the others skip that request const handler = (req, res, next) => { if (handledRequests.has(req)) { return next(); } handledRequests.add(req); return middlewareFunction(req, res, next); }; // The root path goes first: mounted with Express "use()", it then runs // the middleware for every request, with "req.url" left as it is const pathsToApplyMiddleware = paths .map(path => path || '/') .sort((a, b) => Number(b === '/') - Number(a === '/')); pathsToApplyMiddleware.forEach(path => router(path, handler)); } getContextId(request, isTreeDurable) { const contextId = ContextIdFactory.getByRequest(request); if (!request[REQUEST_CONTEXT_ID]) { Object.defineProperty(request, REQUEST_CONTEXT_ID, { value: contextId, enumerable: false, writable: false, configurable: false, }); const requestProviderValue = isTreeDurable ? contextId.payload : Object.assign(request, contextId.payload); this.container.registerRequestProvider(requestProviderValue, contextId); } return contextId; } }