dynamic.module.ts 1.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
import { config } from '../../../config';
import { Environment } from '@/environment';
import { MiddlewareConsumer, Module, NestMiddleware, NestModule } from '@nestjs/common';
import { createProxyMiddleware, RequestHandler } from 'http-proxy-middleware';

export class BaseAccMiddleware implements NestMiddleware {
  /**
   * 代理对象
   *
   * @author chitanda
   * @date 2021-12-10 19:12:38
   * @protected
   * @type {RequestHandler}
   */
  protected proxy?: RequestHandler;

  use(req: any, res: any, next: () => void): void {
    if (!this.proxy) {
      const pathKey = `^${Environment.BasePath}/`;
      const path = `/`;
      this.proxy = createProxyMiddleware({
        target: config.dynamic?.address,
        changeOrigin: true,
        pathRewrite: { [pathKey]: path },
      });
    }
    const url: string = req.originalUrl;
    const urls = url.split('/');
    const newUrls: string[] = [];
    urls.forEach((str, i) => {
      newUrls.push(str);
      if (i === 2) {
        newUrls.push('PSSYSAPPS');
        newUrls.push(config.dynamic?.appName);
      }
    });
    req.originalUrl = newUrls.join('/');
    this.proxy(req, res, next);
  }
}

@Module({})
export class DynamicModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(BaseAccMiddleware).forRoutes('dynamodel/(.*)');
  }
}