Nest.js 从代码的任何地方获取当前请求

huangapple go评论70阅读模式
英文:

Nest.js get current request from anywhere in code

问题

我需要从调用链中深入的服务中访问请求对象。我不想通过参数传递它,因为那将需要进行很多更改。

我尝试过使用请求范围的提供程序来实现它:

@Injectable({ scope: Scope.REQUEST })
export class FetcherService {
  constructor(
    private defaultProductFetcher: DefaultProductFetcher,
    private loopbackFetcher: LoopbackFetcher,
    @Inject(REQUEST) private readonly request: Request,
  ) {}

  // 在这里使用 this.request 来代理头部到其他服务
}

但是,由于某种未知原因,这会阻止应用程序中的所有服务调用onModuleInit,因此应用程序无法正常工作。

  1. 为什么所有的 onModuleInit 方法都受到了影响?
  2. 有没有更好的方法来获取请求信息?
英文:

I need to access request object from a service deep down in the call chain. I don't want to pass it through an argument, because that would be a lot of changes.

I've tried doing it using a request-scoped provider:

@Injectable({ scope: Scope.REQUEST })
export class FetcherService {
  constructor(
    private defaultProductFetcher: DefaultProductFetcher,
    private loopbackFetcher: LoopbackFetcher,
    @Inject(REQUEST) private readonly request: Request,
  ) {}

  // ...use this.request here for proxying headers to other services
}

But this, for some unknown reason, prevents all services in my application from calling onModuleInit and because of this application doesn't work properly.

  1. Why are all onModuleInit methods affected by this?
  2. Is there a better way of getting request information?

答案1

得分: 1

根据这里的文档中所述:

> 上面列出的生命周期钩子不会对请求范围的类触发。 请求范围的类不与应用程序生命周期绑定,它们的生命周期是不可预测的。 它们专为每个请求创建,并在响应发送后自动进行垃圾回收。

如果您正在使用node16,可以使用nestjs-cls

英文:

as stated in the docs here:

> The lifecycle hooks listed above are not triggered for request-scoped classes. Request-scoped classes are not tied to the application lifecycle and their lifespan is unpredictable. They are exclusively created for each request and automatically garbage-collected after the response is sent.

If you're using node16 you could use the nestjs-cls instead.

huangapple
  • 本文由 发表于 2023年7月3日 17:25:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76603457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定