首页 > 解决方案 > 如何从 Nest.js 中的服务触发应用程序关闭?

问题描述

我正在寻找一种方法来从 Nest.js 中的服务触发应用程序关闭,该服务仍将调用钩子。

我有一个案例,当我在服务中处理消息时,在某些情况下这应该关闭应用程序。我曾经抛出未处理的异常,但是当我这样做时,Nest.js 不会调用像我这样的钩子onModuleDestroy甚至关闭钩子onApplicationShutdown,这在我的情况下是必需的。

按预期调用.close()fromINestApplication工作,但我如何将它注入我的服务?或者也许我可以使用其他一些模式来实现我想要做的事情?

非常感谢您提供的所有帮助。

标签: javascriptnode.jstypescriptlifecyclenestjs

解决方案


您不能注入应用程序。相反,您可以从您的服务发出一个关闭事件,让应用程序订阅它,然后在您的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();
  }
}

main.ts

// Subscribe to your service's shutdown event, run app.close() when emitted
app.get(ShutdownService).subscribeToShutdown(() => app.close());

在此处查看运行示例:

从服务中编辑 Nest 关闭


推荐阅读