[英]How to trigger application shutdown from a service in Nest.js?
I'm looking for a way to trigger application shutdown from a service in Nest.js that will still call hooks. 我正在寻找一种方法来从Nest.js中的服务触发应用程序关闭,该服务仍然会调用钩子。
I have a case when I'm handling a message in a service and in some scenario this should shutdown the application. 我遇到一种情况,当我在服务中处理消息时,在某些情况下应关闭应用程序。 I used to throw unhandled exceptions but when I do this Nest.js doesn't call hooks like onModuleDestroy
or even shutdown hooks like onApplicationShutdown
which are required in my case. 我曾经抛出未处理的异常,但是当我做这个Nest.js并不要求像钩子onModuleDestroy
甚至关闭挂钩像onApplicationShutdown
这是需要我的情况。
calling .close()
from INestApplication
works as expected but how do I inject it into my service? 从INestApplication
调用.close()
可以按预期工作,但是如何将其注入到我的服务中呢? Or maybe there is some other pattern I could use to achieve what I'm trying to do? 或者也许我可以使用其他一些模式来实现自己的目标?
Thank you very much for all the help. 非常感谢您提供的所有帮助。
You cannot inject the application. 您无法注入应用程序。 Instead, you can emit a shutdown event from your service, let the application subscribe to it and then trigger the actual shutdown in your main.ts
: 相反,您可以从服务中发出关闭事件,让应用程序订阅它,然后在main.ts
触发实际的关闭:
export class ShutdownService implements OnModuleDestroy {
// Create an rxjs Subject that your application can subscribe to
private shutdownListener$: Subject<void> = new Subject();
// Your hook will be executed
onModuleDestroy() {
console.log('Executing OnDestroy Hook');
}
// Subscribe to the shutdown in your main.ts
subscribeToShutdown(shutdownFn: () => void): void {
this.shutdownListener$.subscribe(() => shutdownFn());
}
// Emit the shutdown event
shutdown() {
this.shutdownListener$.next();
}
}
// Subscribe to your service's shutdown event, run app.close() when emitted
app.get(ShutdownService).subscribeToShutdown(() => app.close());
See a running example here: 在此处查看正在运行的示例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.