|
| 1 | +import type { MiddlewareConfigProxy, MiddlewareConsumer, NestMiddleware, RouteInfo, Type } from '@nestjs/common/interfaces' |
| 2 | +import type { IPluginContext } from '@unioc/core' |
| 3 | +import type { MiddlewareConsumerBuilder } from './middleware-customer' |
| 4 | +import { isClass } from '@unioc/shared' |
| 5 | + |
| 6 | +export interface IResolvedMiddleware { |
| 7 | + handler(...args: any[]): any |
| 8 | + instance?: NestMiddleware |
| 9 | + routes: (string | Type<any> | RouteInfo)[] |
| 10 | +} |
| 11 | + |
| 12 | +export class MiddlewareConfigProxyBuilder implements MiddlewareConfigProxy { |
| 13 | + private _excludedRoutes: (string | RouteInfo)[] = [] |
| 14 | + private _routes: (string | Type<any> | RouteInfo)[] = [] |
| 15 | + private _middleware: (Type<any> | ((...args: any[]) => any))[] = [] |
| 16 | + |
| 17 | + constructor(private readonly _middlewareConsumer: MiddlewareConsumerBuilder) {} |
| 18 | + |
| 19 | + protected getMiddlewareConsumer(): MiddlewareConsumer { |
| 20 | + this._middlewareConsumer.add(this) |
| 21 | + return this._middlewareConsumer |
| 22 | + } |
| 23 | + |
| 24 | + exclude(...routes: (string | RouteInfo)[]): MiddlewareConfigProxy { |
| 25 | + this._excludedRoutes = [...this._excludedRoutes, ...routes] |
| 26 | + return this |
| 27 | + } |
| 28 | + |
| 29 | + forRoutes(...routes: (string | Type<any> | RouteInfo)[]): MiddlewareConsumer { |
| 30 | + this._routes = [...this._routes, ...routes] |
| 31 | + return this.getMiddlewareConsumer() |
| 32 | + } |
| 33 | + |
| 34 | + public getExcludedRoutes(): (string | RouteInfo)[] { |
| 35 | + return this._excludedRoutes |
| 36 | + } |
| 37 | + |
| 38 | + public getRoutes(): (string | Type<any> | RouteInfo)[] { |
| 39 | + return this._routes |
| 40 | + } |
| 41 | + |
| 42 | + public setMiddleware(middleware: (Type<any> | ((...args: any[]) => any))[]): void { |
| 43 | + this._middleware = middleware |
| 44 | + } |
| 45 | + |
| 46 | + public async resolveMiddlewares(ctx: IPluginContext): Promise<IResolvedMiddleware[]> { |
| 47 | + const handlers: IResolvedMiddleware[] = [] |
| 48 | + |
| 49 | + for (const middleware of this._middleware) { |
| 50 | + if (isClass(middleware)) { |
| 51 | + const instance: NestMiddleware = await ctx.createClass(middleware).resolve() |
| 52 | + if (instance && typeof instance === 'object' && 'use' in instance && typeof instance.use === 'function') { |
| 53 | + handlers.push({ |
| 54 | + handler: instance.use, |
| 55 | + instance, |
| 56 | + routes: this._routes, |
| 57 | + }) |
| 58 | + } |
| 59 | + } |
| 60 | + else { |
| 61 | + handlers.push({ |
| 62 | + handler: middleware, |
| 63 | + instance: undefined, |
| 64 | + routes: this._routes, |
| 65 | + }) |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return handlers |
| 70 | + } |
| 71 | +} |
0 commit comments