如何从 Nest.js 中的服务触发应用程序关闭?

How to trigger application shutdown from a service in Nest.js?

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

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

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

非常感谢大家的帮助。

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

在此处查看 运行 示例: