动态模块
模块章节涵盖了 Nest 模块的基础知识,并简要介绍了动态模块。本章将深入探讨动态模块的主题。完成后,你应该对它们是什么、何时以及如何使用它们有一个很好的理解。
简介
文档概述部分中的大多数应用程序代码示例都使用了常规的或静态的模块。模块定义了一组组件,如提供者和控制器,它们组合在一起作为整体应用程序的模块化部分。它们为这些组件提供了执行上下文或作用域。例如,模块中定义的提供者对模块的其他成员可见,无需导出它们。当提供者需要在模块外部可见时,它首先从其宿主模块导出,然后导入到其消费模块中。
让我们通过一个熟悉的例子来说明。
首先,我们将定义一个 UsersModule 来提供和导出 UsersService。UsersModule 是 UsersService 的宿主模块。
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
@Module({
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}接下来,我们将定义一个 AuthModule,它导入 UsersModule,使 UsersModule 导出的提供者在 AuthModule 内部可用:
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { UsersModule } from '../users/users.module';
@Module({
imports: [UsersModule],
providers: [AuthService],
exports: [AuthService],
})
export class AuthModule {}这些构造允许我们在 AuthModule 中托管的 AuthService 中注入 UsersService:
import { Injectable } from '@nestjs/common';
import { UsersService } from '../users/users.service';
@Injectable()
export class AuthService {
constructor(private usersService: UsersService) {}
/*
Implementation that makes use of this.usersService
*/
}我们将其称为静态模块绑定。Nest 将模块连接在一起所需的所有信息已经在宿主和消费模块中声明。让我们解析一下这个过程中发生了什么。Nest 通过以下方式使 UsersService 在 AuthModule 内部可用:
- 实例化
UsersModule,包括传递性地导入UsersModule本身消费的其他模块,以及传递性地解析任何依赖项(参见自定义提供者)。 - 实例化
AuthModule,并使UsersModule导出的提供者对AuthModule中的组件可用(就好像它们是在AuthModule中声明的一样)。 - 在
AuthService中注入UsersService的实例。
动态模块用例
使用静态模块绑定时,消费模块没有机会影响宿主模块中提供者的配置方式。为什么这很重要?考虑这样一种情况:我们有一个通用目的的模块,需要在不同的用例中表现不同。这类似于许多系统中"插件"的概念,其中通用功能在被消费者使用之前需要一些配置。
Nest 中一个很好的例子是配置模块。许多应用程序发现通过使用配置模块来外部化配置细节很有用。这使得在不同部署中动态更改应用程序设置变得容易:例如,开发者使用的开发数据库、暂存/测试环境的暂存数据库等。通过将配置参数的管理委托给配置模块,应用程序源代码保持独立于配置参数。
挑战在于配置模块本身,由于它是通用的(类似于"插件"),需要由其消费模块进行自定义。这就是_动态模块_发挥作用的地方。使用动态模块特性,我们可以使配置模块成为动态的,这样消费模块就可以使用 API 来控制配置模块在导入时如何被自定义。
换句话说,动态模块提供了一个 API,用于将一个模块导入到另一个模块中,并在导入时自定义该模块的属性和行为,而不是使用我们到目前为止看到的静态绑定。
配置模块示例
我们将使用配置章节中示例代码的基本版本。本章结束时的完成版本可作为工作示例在此处获取。
我们的需求是使 ConfigModule 接受一个 options 对象来自定义它。这是我们想要支持的功能。基本示例将 .env 文件的位置硬编码为项目根文件夹。假设我们想使其可配置,以便你可以在你选择的任何文件夹中管理 .env 文件。例如,假设你想将各种 .env 文件存储在项目根目录下名为 config 的文件夹中(即 src 的同级文件夹)。你希望在不同项目中使用 ConfigModule 时能够选择不同的文件夹。
动态模块使我们能够将参数传递给正在导入的模块,以便我们可以更改其行为。让我们看看这是如何工作的。从消费模块的角度来看,从最终目标开始然后向后推导会很有帮助。首先,让我们快速回顾一下_静态_导入 ConfigModule 的示例(即一种无法影响导入模块行为的方法)。注意 @Module() 装饰器中的 imports 数组:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from './config/config.module';
@Module({
imports: [ConfigModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}让我们考虑一下_动态模块_导入可能是什么样子,其中我们传入一个配置对象。比较这两个示例中 imports 数组的差异:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from './config/config.module';
@Module({
imports: [ConfigModule.register({ folder: './config' })],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}让我们看看上面的动态示例中发生了什么。有哪些动态部分?
ConfigModule是一个普通类,所以我们可以推断它必须有一个名为register()的静态方法。我们知道它是静态的,因为我们在ConfigModule类上调用它,而不是在类的实例上。注意:这个我们即将创建的方法可以有任意名称,但按照惯例我们应该将其命名为forRoot()或register()。register()方法由我们定义,所以我们可以接受任何我们喜欢的输入参数。在本例中,我们将接受一个具有适当属性的简单options对象,这是典型的情况。- 我们可以推断
register()方法必须返回类似于module的东西,因为它的返回值出现在我们到目前为止看到的熟悉的imports列表中,该列表包含模块列表。
实际上,我们的 register() 方法将返回一个 DynamicModule。动态模块只不过是在运行时创建的模块,具有与静态模块完全相同的属性,外加一个名为 module 的附加属性。让我们快速回顾一个静态模块声明示例,注意传递给装饰器的模块选项:
@Module({
imports: [DogsModule],
controllers: [CatsController],
providers: [CatsService],
exports: [CatsService]
})动态模块必须返回一个具有完全相同接口的对象,外加一个名为 module 的附加属性。module 属性用作模块的名称,应与模块的类名相同,如下面的示例所示。
提示
对于动态模块,模块选项对象的所有属性都是可选的,除了 module。
那么静态 register() 方法呢?我们现在可以看到它的任务是返回一个具有 DynamicModule 接口的对象。当我们调用它时,我们实际上是在向 imports 列表提供一个模块,类似于我们在静态情况下通过列出模块类名所做的方式。换句话说,动态模块 API 只是返回一个模块,但不是在 @Module 装饰器中固定属性,而是以编程方式指定它们。
仍有几个细节需要涵盖,以帮助完善全貌:
- 我们现在可以说明
@Module()装饰器的imports属性不仅可以接受模块类名(例如imports: [UsersModule]),还可以接受返回动态模块的函数(例如imports: [ConfigModule.register(...)])。 - 动态模块本身可以导入其他模块。在这个示例中我们不会这样做,但如果动态模块依赖于其他模块的提供者,你可以使用可选的
imports属性导入它们。同样,这与你使用@Module()装饰器为静态模块声明元数据的方式完全类似。
有了这种理解,我们现在可以看看动态 ConfigModule 声明必须是什么样子。让我们尝试一下。
import { DynamicModule, Module } from '@nestjs/common';
import { ConfigService } from './config.service';
@Module({})
export class ConfigModule {
static register(): DynamicModule {
return {
module: ConfigModule,
providers: [ConfigService],
exports: [ConfigService],
};
}
}现在应该清楚各部分是如何联系在一起的。调用 ConfigModule.register(...) 返回一个 DynamicModule 对象,其属性本质上与我们迄今为止通过 @Module() 装饰器作为元数据提供的属性相同。
提示
从 @nestjs/common 导入 DynamicModule。
然而,我们的动态模块还不是很有趣,因为我们还没有引入任何配置它的能力,正如我们说过的那样。让我们接下来解决这个问题。
模块配置
自定义 ConfigModule 行为的显而易见的解决方案是在静态 register() 方法中传递一个 options 对象,正如我们上面猜测的那样。让我们再次看看消费模块的 imports 属性:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from './config/config.module';
@Module({
imports: [ConfigModule.register({ folder: './config' })],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}这很好地处理了将 options 对象传递给动态模块的问题。那我们如何在 ConfigModule 中使用该 options 对象呢?让我们想一想。我们知道 ConfigModule 基本上是一个宿主,用于提供和导出可注入的服务——ConfigService——供其他提供者使用。实际上是我们的 ConfigService 需要读取 options 对象来自定义其行为。让我们暂时假设我们知道如何以某种方式将 options 从 register() 方法传递到 ConfigService。有了这个假设,我们可以对服务进行一些更改,以根据 options 对象的属性自定义其行为。(注意:目前,由于我们_还没有_确定如何传递它,我们将只是硬编码 options。我们马上会修复这个问题。)
import { Injectable } from '@nestjs/common';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as dotenv from 'dotenv';
import { EnvConfig } from './interfaces';
@Injectable()
export class ConfigService {
private readonly envConfig: EnvConfig;
constructor() {
const options = { folder: './config' };
const filePath = `${process.env.NODE_ENV || 'development'}.env`;
const envFile = path.resolve(__dirname, '../../', options.folder, filePath);
this.envConfig = dotenv.parse(fs.readFileSync(envFile));
}
get(key: string): string {
return this.envConfig[key];
}
}现在我们的 ConfigService 知道如何在我们在 options 中指定的文件夹中找到 .env 文件。
我们剩下的任务是以某种方式将 register() 步骤中的 options 对象注入到我们的 ConfigService 中。当然,我们将使用_依赖注入_来做到这一点。这是一个关键点,所以确保你理解它。我们的 ConfigModule 提供 ConfigService。ConfigService 反过来依赖于仅在运行时提供的 options 对象。因此,在运行时,我们需要首先将 options 对象绑定到 Nest IoC 容器,然后让 Nest 将其注入到我们的 ConfigService 中。请记住,从自定义提供者章节中,提供者可以包含任何值而不仅仅是服务,所以我们可以使用依赖注入来处理简单的 options 对象。
让我们先处理将 options 对象绑定到 IoC 容器。我们在静态 register() 方法中执行此操作。请记住,我们正在动态构建一个模块,模块的属性之一是其提供者列表。因此,我们需要做的是将 options 对象定义为提供者。这将使其可注入到 ConfigService 中,我们将在下一步中利用这一点。在下面的代码中,注意 providers 数组:
import { DynamicModule, Module } from '@nestjs/common';
import { ConfigService } from './config.service';
@Module({})
export class ConfigModule {
static register(options: Record<string, any>): DynamicModule {
return {
module: ConfigModule,
providers: [
{
provide: 'CONFIG_OPTIONS',
useValue: options,
},
ConfigService,
],
exports: [ConfigService],
};
}
}现在我们可以通过将 'CONFIG_OPTIONS' 提供者注入到 ConfigService 中来完成这个过程。回想一下,当我们使用非类令牌定义提供者时,我们需要使用 @Inject() 装饰器如此处所述。
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as dotenv from 'dotenv';
import { Injectable, Inject } from '@nestjs/common';
import { EnvConfig } from './interfaces';
@Injectable()
export class ConfigService {
private readonly envConfig: EnvConfig;
constructor(@Inject('CONFIG_OPTIONS') private options: Record<string, any>) {
const filePath = `${process.env.NODE_ENV || 'development'}.env`;
const envFile = path.resolve(__dirname, '../../', options.folder, filePath);
this.envConfig = dotenv.parse(fs.readFileSync(envFile));
}
get(key: string): string {
return this.envConfig[key];
}
}最后一点说明:为简单起见,我们在上面使用了基于字符串的注入令牌('CONFIG_OPTIONS'),但最佳实践是在单独的文件中将其定义为常量(或 Symbol),然后导入该文件。例如:
export const CONFIG_OPTIONS = 'CONFIG_OPTIONS';示例
本章代码的完整示例可以在此处找到。
社区指南
你可能在一些 @nestjs/ 包中看到过 forRoot、register 和 forFeature 等方法的使用,可能想知道这些方法之间有什么区别。对此没有硬性规则,但 @nestjs/ 包尝试遵循以下指南:
创建模块时:
register,你期望配置一个动态模块,该配置仅供调用模块使用。例如,使用 Nest 的@nestjs/axios:HttpModule.register({ baseUrl: 'someUrl' })。如果在另一个模块中使用HttpModule.register({ baseUrl: 'somewhere else' }),它将具有不同的配置。你可以为任意多的模块执行此操作。forRoot,你期望配置一次动态模块,并在多个地方重用该配置(尽管可能不知不觉地,因为它被抽象了)。这就是为什么你有一个GraphQLModule.forRoot()、一个TypeOrmModule.forRoot()等。forFeature,你期望使用动态模块forRoot的配置,但需要修改一些特定于调用模块需求的配置(即该模块应该访问哪个仓库,或日志记录器应该使用的上下文。)
所有这些通常也有其 async 对应方法,registerAsync、forRootAsync 和 forFeatureAsync,含义相同,但使用 Nest 的依赖注入来进行配置。
可配置模块构建器
由于手动创建高度可配置的、暴露 async 方法(registerAsync、forRootAsync 等)的动态模块非常复杂,特别是对于新手来说,Nest 公开了 ConfigurableModuleBuilder 类,它促进了这个过程,让你只需几行代码就可以构建模块"蓝图"。
例如,让我们以上面使用的示例(ConfigModule)为例,将其转换为使用 ConfigurableModuleBuilder。在开始之前,让我们确保创建一个专用接口,表示 ConfigModule 接受的选项。
export interface ConfigModuleOptions {
folder: string;
}有了这个,创建一个新的专用文件(与现有的 config.module.ts 文件并列)并将其命名为 config.module-definition.ts。在此文件中,让我们利用 ConfigurableModuleBuilder 来构造 ConfigModule 定义。
// config.module-definition.ts
import { ConfigurableModuleBuilder } from '@nestjs/common';
import { ConfigModuleOptions } from './interfaces/config-module-options.interface';
export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
new ConfigurableModuleBuilder<ConfigModuleOptions>().build();现在让我们打开 config.module.ts 文件并修改其实现以利用自动生成的 ConfigurableModuleClass:
import { Module } from '@nestjs/common';
import { ConfigService } from './config.service';
import { ConfigurableModuleClass } from './config.module-definition';
@Module({
providers: [ConfigService],
exports: [ConfigService],
})
export class ConfigModule extends ConfigurableModuleClass {}扩展 ConfigurableModuleClass 意味着 ConfigModule 现在不仅提供 register 方法(如之前的自定义实现),还提供 registerAsync 方法,允许消费者异步配置该模块,例如通过提供异步工厂:
@Module({
imports: [
ConfigModule.register({ folder: './config' }),
// 或者:
// ConfigModule.registerAsync({
// useFactory: () => {
// return {
// folder: './config',
// }
// },
// inject: [...any extra dependencies...]
// }),
],
})
export class AppModule {}registerAsync 方法接受以下对象作为参数:
{
/**
* 注入令牌,解析为将被实例化为提供者的类。
* 该类必须实现相应的接口。
*/
useClass?: Type<
ConfigurableModuleOptionsFactory<ModuleOptions, FactoryClassMethodKey>
>;
/**
* 返回选项(或解析为选项的 Promise)以配置模块的函数。
*/
useFactory?: (...args: any[]) => Promise<ModuleOptions> | ModuleOptions;
/**
* 工厂可能注入的依赖项。
*/
inject?: FactoryProvider['inject'];
/**
* 注入令牌,解析为现有提供者。该提供者必须实现
* 相应的接口。
*/
useExisting?: Type<
ConfigurableModuleOptionsFactory<ModuleOptions, FactoryClassMethodKey>
>;
}让我们逐一介绍上述属性:
useFactory- 返回配置对象的函数。它可以是同步的或异步的。要将依赖项注入到工厂函数中,使用inject属性。我们在上面的示例中使用了这种变体。inject- 将注入到工厂函数中的依赖项数组。依赖项的顺序必须与工厂函数中参数的顺序匹配。useClass- 将被实例化为提供者的类。该类必须实现相应的接口。通常,这是一个提供create()方法来返回配置对象的类。在下面的自定义方法键部分中了解更多信息。useExisting-useClass的变体,允许你使用现有提供者而不是指示 Nest 创建类的新实例。当你想使用模块中已注册的提供者时,这很有用。请记住,该类必须实现与useClass中使用的相同接口(因此它必须提供create()方法,除非你覆盖默认方法名称,请参阅下面的自定义方法键部分)。
始终选择上述选项之一(useFactory、useClass 或 useExisting),因为它们是互斥的。
最后,让我们更新 ConfigService 类以注入生成的模块选项提供者,而不是我们到目前为止使用的 'CONFIG_OPTIONS'。
@Injectable()
export class ConfigService {
constructor(@Inject(MODULE_OPTIONS_TOKEN) private options: ConfigModuleOptions) { ... }
}自定义方法键
ConfigurableModuleClass 默认提供 register 及其对应的 registerAsync 方法。要使用不同的方法名称,使用 ConfigurableModuleBuilder#setClassMethodName 方法,如下所示:
// config.module-definition.ts
export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
new ConfigurableModuleBuilder<ConfigModuleOptions>().setClassMethodName('forRoot').build();此构造将指示 ConfigurableModuleBuilder 生成一个暴露 forRoot 和 forRootAsync 而不是 register 和 registerAsync 的类。示例:
@Module({
imports: [
ConfigModule.forRoot({ folder: './config' }), // <-- 注意使用 "forRoot" 而不是 "register"
// 或者:
// ConfigModule.forRootAsync({
// useFactory: () => {
// return {
// folder: './config',
// }
// },
// inject: [...any extra dependencies...]
// }),
],
})
export class AppModule {}自定义选项工厂类
由于 registerAsync 方法(或 forRootAsync 或任何其他名称,取决于配置)让消费者传递解析为模块配置的提供者定义,库消费者可能会提供一个用于构造配置对象的类。
@Module({
imports: [
ConfigModule.registerAsync({
useClass: ConfigModuleOptionsFactory,
}),
],
})
export class AppModule {}默认情况下,此类必须提供返回模块配置对象的 create() 方法。但是,如果你的库遵循不同的命名约定,你可以更改该行为并指示 ConfigurableModuleBuilder 期望不同的方法,例如 createConfigOptions,使用 ConfigurableModuleBuilder#setFactoryMethodName 方法:
// config.module-definition.ts
export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
new ConfigurableModuleBuilder<ConfigModuleOptions>().setFactoryMethodName('createConfigOptions').build();现在,ConfigModuleOptionsFactory 类必须暴露 createConfigOptions 方法(而不是 create):
@Module({
imports: [
ConfigModule.registerAsync({
useClass: ConfigModuleOptionsFactory, // <-- 此类必须提供 "createConfigOptions" 方法
}),
],
})
export class AppModule {}额外选项
有些边缘情况下,你的模块可能需要接受额外的选项来确定其行为方式(这类选项的一个很好的例子是 isGlobal 标志——或简称 global),但同时不应包含在 MODULE_OPTIONS_TOKEN 提供者中(因为它们与该模块内注册的服务/提供者无关,例如 ConfigService 不需要知道其宿主模块是否注册为全局模块)。
在这种情况下,可以使用 ConfigurableModuleBuilder#setExtras 方法。请参阅以下示例:
export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
new ConfigurableModuleBuilder<ConfigModuleOptions>()
.setExtras(
{
isGlobal: true,
},
(definition, extras) => ({
...definition,
global: extras.isGlobal,
}),
)
.build();在上面的示例中,传递给 setExtras 方法的第一个参数是包含"额外"属性默认值的对象。第二个参数是一个函数,接受自动生成的模块定义(包含 provider、exports 等)和表示额外属性的 extras 对象(由消费者指定或默认值)。此函数的返回值是修改后的模块定义。在这个特定示例中,我们获取 extras.isGlobal 属性并将其分配给模块定义的 global 属性(这反过来决定模块是否是全局的,在此处了解更多)。
现在,在使用此模块时,可以传入额外的 isGlobal 标志,如下所示:
@Module({
imports: [
ConfigModule.register({
isGlobal: true,
folder: './config',
}),
],
})
export class AppModule {}但是,由于 isGlobal 被声明为"额外"属性,它不会在 MODULE_OPTIONS_TOKEN 提供者中可用:
@Injectable()
export class ConfigService {
constructor(
@Inject(MODULE_OPTIONS_TOKEN) private options: ConfigModuleOptions,
) {
// "options" 对象不会有 "isGlobal" 属性
// ...
}
}扩展自动生成的方法
自动生成的静态方法(register、registerAsync 等)可以根据需要进行扩展,如下所示:
import { Module } from '@nestjs/common';
import { ConfigService } from './config.service';
import {
ConfigurableModuleClass,
ASYNC_OPTIONS_TYPE,
OPTIONS_TYPE,
} from './config.module-definition';
@Module({
providers: [ConfigService],
exports: [ConfigService],
})
export class ConfigModule extends ConfigurableModuleClass {
static register(options: typeof OPTIONS_TYPE): DynamicModule {
return {
// your custom logic here
...super.register(options),
};
}
static registerAsync(options: typeof ASYNC_OPTIONS_TYPE): DynamicModule {
return {
// your custom logic here
...super.registerAsync(options),
};
}
}注意使用必须从模块定义文件中导出的 OPTIONS_TYPE 和 ASYNC_OPTIONS_TYPE 类型:
export const {
ConfigurableModuleClass,
MODULE_OPTIONS_TOKEN,
OPTIONS_TYPE,
ASYNC_OPTIONS_TYPE,
} = new ConfigurableModuleBuilder<ConfigModuleOptions>().build();