Nestjs 请求和应用程序生命周期

Nestjs Request and Application Lifecycle

我正在寻找有关 NestJS 框架的请求和应用程序生命周期的信息。具体来说:

  1. 请求中以下进程的执行顺序是什么,对于实现的路由:中间件、管道、守卫、拦截器和任何其他潜在的请求进程

  2. NestJS 应用程序中模块和提供程序的生命周期是多少?它们是否在请求、应用程序或其他东西的生命周期内持续存在?

  3. 除了 OnModuleInit 和 OnModuleDestroy 之外,还有生命周期钩子吗?

  4. 是什么导致模块被销毁(并触发 OnModuleDestroy 事件)?

What is the order of execution of the following processes in a request, for a route that implements: middleware, pipes, guards, interceptors, and any other potential request process

常见的顺序是:

  • 中间件
  • 守卫
  • 拦截器(在操作流之前)
  • 管道
  • 拦截器(操作流后)
  • 异常过滤器(如果捕获到任何异常)

What is the lifespan of modules and providers in a NestJS application? Do they last for the lifespan of a request, or the application, or something else?

它们确实会在应用程序的整个生命周期内持续存在。当 NestApplication 或 NestMicroservice 被关闭时,模块被销毁(参见 INestApplication 中的 close 方法)。

Are there any lifecycle hooks, in addition to OnModuleInit and OnModuleDestroy?

暂时没有。

What causes a Modeule to be destroyed (and trigger the OnModuleDestroy event)?

看我对第二点的回答。当您看起来对生命周期挂钩感兴趣时,您可能会对问题 #938 and #550

感兴趣

What is the order of execution of the following processes in a request, for a route that implements: middleware, pipes, guards, interceptors, and any other potential request process

Middleware -> Guards -> Interceptors (code before next.handle()) -> Pipes -> Route Handler -> Interceptors (eg: next.handle().pipe( tap(() => changeResponse()) ) ) -> Exception Filter (如果抛出异常)

对于这三个,您可以在它们的构造函数中注入其他依赖项(如服务等)。

What is the lifespan of modules and providers in a NestJS application? Do they last for the lifespan of a request, or the application, or something else?

提供商可以具有以下任何范围:

SINGLETON - 提供程序的单个实例在整个应用程序中共享。实例生命周期与应用程序生命周期直接相关。应用程序启动后,所有单例提供程序都已实例化。默认使用单例范围。

REQUEST - 专门为每个传入请求创建提供程序的新实例。请求处理完成后实例将被垃圾回收。

TRANSIENT - 临时提供者不在消费者之间共享。每个注入临时提供者的消费者都会收到一个新的专用实例。

对于大多数用例,建议使用单例范围。跨消费者和跨请求共享提供者意味着可以缓存一个实例,并且它的初始化只发生一次,在应用程序启动期间。

例子

import { Injectable, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.REQUEST })
export class CatsService {}

Are there any lifecycle hooks, in addition to OnModuleInit and OnModuleDestroy?

OnApplicationBootstrap - 在应用程序完全启动并启动后调用 OnApplicationShutdown - 响应系统信号(当应用程序被例如 SIGTERM 关闭时)。使用此挂钩可以优雅地关闭 Nest 应用程序。此功能通常与 Kubernetes、Heroku 或类似服务一起使用。

OnModuleInitOnApplicationBootstrap 挂钩都允许您推迟应用程序初始化过程(return Promise 或将方法标记为异步)。

What causes a Module to be destroyed (and trigger the OnModuleDestroy event)?

通常来自 Kubernetes、Heroku 或类似服务的关闭信号。