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.

152 lines (151 loc) • 6.82 kB
import { inspect } from 'util'; import { InvalidMiddlewareConfigurationException } from '../errors/exceptions/invalid-middleware-configuration.exception.js'; import { MetadataScanner } from '../metadata-scanner.js'; import { PathsExplorer } from '../router/paths-explorer.js'; import { isRequestMethodAll } from '../router/utils/index.js'; import { MODULE_PATH, PATH_METADATA, VERSION_METADATA, addLeadingSlash, isFunction, isObject, isString, isUndefined, stripEndSlash, } from '@nestjs/common/internal'; import { RequestMethod } from '@nestjs/common'; export class RoutesMapper { container; applicationConfig; pathsExplorer; constructor(container, applicationConfig) { this.container = container; this.applicationConfig = applicationConfig; this.pathsExplorer = new PathsExplorer(new MetadataScanner()); } mapRouteToRouteInfo(controllerOrRoute) { if (isString(controllerOrRoute)) { return this.getRouteInfoFromPath(controllerOrRoute); } const routePathOrPaths = this.getRoutePath(controllerOrRoute); if (this.isRouteInfo(routePathOrPaths, controllerOrRoute)) { return this.getRouteInfoFromObject(controllerOrRoute); } if (isUndefined(routePathOrPaths)) { // Neither a controller nor a { path, method } object (e.g. a class // without @Controller()): the middleware would be bound to a route no // request matches, without a word throw new InvalidMiddlewareConfigurationException(isFunction(controllerOrRoute) ? `"${controllerOrRoute.name}" passed to forRoutes() or exclude() is not a controller (is the @Controller() decorator missing?).` : `${inspect(controllerOrRoute, { depth: 2 })} passed to forRoutes() or exclude() is not a { path, method } object where method is a RequestMethod.`); } return this.getRouteInfoFromController(controllerOrRoute, routePathOrPaths); } /** * Returns the routes of every controller of the application, as * `forRoutes()` maps a controller. */ mapControllersToRouteInfo() { const controllers = new Set(); for (const moduleRef of this.container.getModules().values()) { for (const { metatype } of moduleRef.controllers.values()) { if (metatype) { controllers.add(metatype); } } } return [...controllers].flatMap(controller => this.mapRouteToRouteInfo(controller)); } getRouteInfoFromPath(routePath) { const defaultRequestMethod = -1; return [ { path: addLeadingSlash(routePath), method: defaultRequestMethod, }, ]; } getRouteInfoFromObject(routeInfoObject) { const routeInfo = { path: addLeadingSlash(routeInfoObject.path), method: routeInfoObject.method, }; if (routeInfoObject.version) { routeInfo.version = routeInfoObject.version; } return [routeInfo]; } getRouteInfoFromController(controller, routePath) { const controllerPaths = this.pathsExplorer.scanForPaths(Object.create(controller), controller.prototype); const controllerVersion = this.getVersionMetadata(controller); const versioningConfig = this.applicationConfig.getVersioning(); const modulePaths = this.getModulePathsOfController(controller); const concatPaths = (acc, currentValue) => acc.concat(currentValue); const toRouteInfo = (item, prefix, modulePath) => item.path?.flatMap(p => { const endpointPath = modulePath + stripEndSlash(this.normalizeGlobalPath(prefix)) + addLeadingSlash(p); const routeInfo = { path: endpointPath, method: item.requestMethod, }; // A VERSION_NEUTRAL route is kept apart from a route without a // version, which is also served under the default version const version = item.version ?? controllerVersion; if (version && versioningConfig) { if (typeof version !== 'string' && Array.isArray(version)) { return version.map((v) => ({ ...routeInfo, version: v, })); } routeInfo.version = version; } return routeInfo; }); return [] .concat(routePath) .flatMap(routePath => modulePaths.map(modulePath => controllerPaths .map(item => toRouteInfo(item, routePath, modulePath)) .reduce(concatPaths, []))) .reduce(concatPaths, []); } isRouteInfo(path, objectOrClass) { if (!isUndefined(path) || !isObject(objectOrClass)) { return false; } const { path: routePath, method } = objectOrClass; return (isString(routePath) && typeof method === 'number' && // -1 is the "every method" of a route passed as a plain string (!isUndefined(RequestMethod[method]) || isRequestMethodAll(method))); } normalizeGlobalPath(path) { const prefix = addLeadingSlash(path); return prefix === '/' ? '' : prefix; } getRoutePath(route) { return Reflect.getMetadata(PATH_METADATA, route); } /** * Returns the paths the controller is served under: the router registers it * once for each module that declares it, under the path of that module. */ getModulePathsOfController(metatype) { const modulePaths = this.getHostModulesOfController(metatype).map(moduleRef => stripEndSlash(this.getModulePath(moduleRef.metatype) ?? '')); return modulePaths.length > 0 ? [...new Set(modulePaths)] : ['']; } getHostModulesOfController(metatype) { if (!metatype) { return []; } const modulesContainer = this.container.getModules(); return Array.from(modulesContainer.values()).filter(({ controllers }) => controllers.has(metatype)); } getModulePath(metatype) { if (!metatype) { return; } const modulesContainer = this.container.getModules(); const modulePath = Reflect.getMetadata(MODULE_PATH + modulesContainer.applicationId, metatype); return modulePath ?? Reflect.getMetadata(MODULE_PATH, metatype); } getVersionMetadata(metatype) { const versioningConfig = this.applicationConfig.getVersioning(); if (versioningConfig) { return (Reflect.getMetadata(VERSION_METADATA, metatype) ?? versioningConfig.defaultVersion); } } }