typescript - NestJS,在生产中放置控制器或路由
问题描述
在我以前的项目中(在使用 NestJS 之前),我构建了一个有用的实用程序,称为“路由收集器”。基本上,它只是递归地收集路由并将其附加到 Express 应用程序。我可以使用 ts 装饰器和元数据反射 API 来改变它的行为,例如:
@Controller("/test")
class TestController {
@Test
@Get("/")
private testRoute() {
// code
}
}
如果NODE_ENV设置为production,@Test
装饰器将使路由收集器“忽略” 。我想在 NestJS 中获得这种行为,但无法提供代码。testRoute
有没有人实施过这样的事情?如果是这样,我很想得到一些提示。
解决方案
你可以做一个全球后卫。(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);
推荐阅读
- .net - 无论如何在运行时向服务提供者添加服务?还是重建它?在 .NET 5.0 或 .NET core 3+ 上
- reactjs - React-Query 和 NextJS 获取数据将循环结构转换为 JSON 错误
- javascript - 从按钮单击时放置和删除背景颜色
- javascript - 子键的 orderByValue
- reactjs - 如何从 React Hooks 中的嵌套子级更改父级的状态?
- spring - log4j2.properties 未正确读取 VMargument 值
- python - 将 Python 代码编译为可执行文件的方法
- database - 在 Fedora 中安装 Oracle 11 - 18 企业版
- brython - 如何在 brython 中导入 pyodbc?
- azure-active-directory - 如何使用 Web 应用程序中的 MS Graph API 主持团队在线会议