英文:
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
,因此应用程序无法正常工作。
- 为什么所有的
onModuleInit
方法都受到了影响? - 有没有更好的方法来获取请求信息?
英文:
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.
- Why are all
onModuleInit
methods affected by this? - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论