首页 > 解决方案 > NestJS,在生产中放置控制器或路由

问题描述

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

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

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

有没有人实施过这样的事情?如果是这样,我很想得到一些提示。

标签: typescriptbackendnestjs

解决方案


你可以做一个全球后卫。(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);

推荐阅读