import type { InjectionToken, Type } from '@nestjs/common'; import { getClassScope } from '../helpers/get-class-scope.js'; import { isDurable } from '../helpers/is-durable.js'; import { NestContainer } from '../injector/container.js'; import { InstanceWrapper } from '../injector/instance-wrapper.js'; import type { MiddlewareConfiguration } from '@nestjs/common/internal'; export class MiddlewareContainer { private readonly middleware = new Map< string, Map >(); private readonly configurationSets = new Map< string, Set >(); constructor(private readonly container: NestContainer) {} public getMiddlewareCollection( moduleKey: string, ): Map { if (!this.middleware.has(moduleKey)) { const moduleRef = this.container.getModuleByKey(moduleKey)!; this.middleware.set(moduleKey, moduleRef.middlewares); } return this.middleware.get(moduleKey)!; } public getConfigurations(): Map> { return this.configurationSets; } public insertConfig( configList: MiddlewareConfiguration[], moduleKey: string, ) { const middleware = this.getMiddlewareCollection(moduleKey); const targetConfig = this.getTargetConfig(moduleKey)!; const configurations = configList || []; const insertMiddleware = >(metatype: T) => { const token = metatype; middleware.set( token, new InstanceWrapper({ scope: getClassScope(metatype), durable: isDurable(metatype), name: token?.name ?? token, metatype, token, }), ); }; configurations.forEach(config => { [].concat(config.middleware).map(insertMiddleware); targetConfig.add(config); }); } private getTargetConfig(moduleName: string) { if (!this.configurationSets.has(moduleName)) { this.configurationSets.set( moduleName, new Set(), ); } return this.configurationSets.get(moduleName); } }