【问题标题】:NestJS, drop controllers or routes in productionNestJS,在生产中放置控制器或路由
【发布时间】:2020-10-12 06:36:44
【问题描述】:

在我之前的项目中(在使用 NestJS 之前),我构建了一个有用的实用程序,称为“路由收集器”。基本上,它只是递归地收集路由并将其附加到 Express 应用程序。我可以使用 ts 装饰器和元数据反射 API 来改变它的行为,例如:

@Controller("/test")
class TestController {
  @Test
  @Get("/")
  private testRoute() {
    // code
  }
}

如果 NODE_ENV 设置为 production@Test 装饰器将使路由收集器“忽略”testRoute。 我想在 NestJS 中实现这种行为,但无法提供代码。

有没有人实现过类似的东西?如果是这样,我很想得到一些提示。

【问题讨论】:

    标签: typescript backend nestjs


    【解决方案1】:

    你可以做一个全局守卫。 (https://docs.nestjs.com/guards)

    @Module({
      providers: [
        {
          provide: APP_GUARD,
          useClass: TestGuard,
        },
      ],
    })
    export class AppModule {}
    

    测试守卫:

    export class TestGuard implements CanActivate {
      constructor(private readonly reflector: Reflector) {}
    
      canActivate(context: ExecutionContext): boolean {
        const testOnly =  this.reflector.get<boolean>('testonly', context.getHandler());
        // return false if node_env is prod and the test decorator is set
     }
    }
    

    装饰器是这样的:

    export const Test = () => SetMetadata('testonly', true);
    

    【讨论】:

      猜你喜欢
      • 2019-12-12
      • 2020-05-06
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 2018-05-31
      • 1970-01-01
      • 2015-01-26
      相关资源
      最近更新 更多