【问题标题】:NestJS @Injectable used in a global object: use 'new injectable' or 'app.use(injectable)'?NestJS @Injectable 在全局对象中使用:使用“new injectionable”还是“app.use(injectable)”?
【发布时间】:2019-09-17 04:47:08
【问题描述】:

由于 NestJS 允许注入,我想确保我编写最有效的代码。

我正在使用全局拦截器来包装我的应用响应,并使用全局过滤器来处理异常。

//main.ts:
app.useGlobalInterceptors(new ResponseWrapperInterceptor(app.get(LogService)));
app.useGlobalFilters(new ExceptionsFilter(app.get(LogService)));
//filter/interceptor.ts:
constructor(@Inject('LogService') private readonly logger: LogService) {}

在我的 main.ts 中,什么更有效?这两种选择有什么影响?有没有更好的办法?

//Option 1:
app.useGlobalInterceptors(new ResponseWrapperInterceptor(app.get(LogService)));
app.useGlobalFilters(new ExceptionsFilter(app.get(LogService)));

//Option 2:
app.useGlobalInterceptors(new ResponseWrapperInterceptor(new LogService()));
app.useGlobalFilters(new ExceptionsFilter(new LogService()));

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    关于影响或哪种方式更好,我不能说太多;但是,如果您正在寻找一种让 Nest 处理依赖注入的方法,而不必这样做,您可以在 AppModule 中注册您的拦截器和过滤器,如下所示:

    @Module({
      imports: [/* your imports here*/],
      providers: [
        {
          provide: APP_INTERCEPTOR,
          useClass: ResponseWrapperInterceptor
        }, {
          provide: APP_FILTER,
          useClass: ExceptionsFilter
        }
      ]
    })
    export class AppModule {}
    

    其中APP_INTERCEPTORAPP_FILTER 是从@nestjs/core 导入的。 You can read more about it here.

    【讨论】:

    • 感谢您的快速回答。是的,这是我的第一种方法,但是过滤器和拦截器都将用于我的应用程序中的每个模块,如果不需要,我不想在每个模块中声明它们。目标是拥有一组可以在所有新 REST API 中重用的通用模块,以一种简单的方式记录和包装异常和响应。为此,在 main 中将它们标记为全局会更容易
    • 这仍将创建一个全局拦截器以在整个应用程序中使用。引用文档:When using this approach to perform dependency injection for the interceptor, note that regardless of the module where this construction is employed, the interceptor is, in fact, global. 以这种方式绑定时,它仍然应该是您的应用程序的全局拦截器和过滤器
    • 如果我把它放在 AppModule 中,是的,你是对的。这两种方法都有效,也许我应该做一些分析并检查大负载的速度和内存使用情况。谢谢!
    猜你喜欢
    • 2020-12-13
    • 2019-01-19
    • 2018-01-05
    • 2020-04-27
    • 2020-08-25
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2021-05-11
    相关资源
    最近更新 更多