Nestjs 使用joi进行自定义配置模块验证
因此,我遵循了如何为我的Nest应用程序创建配置的指南 由于我有许多配置部分,我想将这些部分拆分为多个配置服务。因此,myapp.module.ts导入一个自定义配置模块Nestjs 使用joi进行自定义配置模块验证,nestjs,joi,Nestjs,Joi,因此,我遵循了如何为我的Nest应用程序创建配置的指南 由于我有许多配置部分,我想将这些部分拆分为多个配置服务。因此,myapp.module.ts导入一个自定义配置模块 @Module({ imports: [CustomConfigModule] }) export class AppModule {} @Module({ imports: [ConfigModule.forRoot()], providers: [ServerConfigService], export
@Module({
imports: [CustomConfigModule]
})
export class AppModule {}
@Module({
imports: [ConfigModule.forRoot()],
providers: [ServerConfigService],
exports: [ServerConfigService],
})
export class CustomConfigModule {}
此自定义配置模块(config.module.ts)绑定所有配置服务并加载嵌套配置模块
@Module({
imports: [CustomConfigModule]
})
export class AppModule {}
@Module({
imports: [ConfigModule.forRoot()],
providers: [ServerConfigService],
exports: [ServerConfigService],
})
export class CustomConfigModule {}
最后,我有一个简单的配置服务server.config.service.ts,它返回应用程序运行的端口
@Injectable()
export class ServerConfigService {
constructor(private readonly configService: ConfigService) {}
public get port(): number {
return this.configService.get<number>('SERVER_PORT');
}
}
@Injectable()
导出类ServerConfigService{
构造函数(私有只读configService:configService){}
公共获取端口():编号{
返回此.configService.get('SERVER_PORT');
}
}
我想在应用程序启动时验证这些服务。这些文档解释了如何为配置模块设置validationschema
在使用自定义配置模块时,如何将其用于服务验证?
我是否必须在每个服务构造函数中调用joi并验证其中的属性
提前感谢我相信您的
ConfigModule.forRoot()
可以设置验证架构并告诉Nest在启动时运行验证,而不必将其添加到每个自定义配置服务中。文档显示如下内容:
@Module({
imports: [
ConfigModule.forRoot({
validationSchema: Joi.object({
NODE_ENV: Joi.string()
.valid('development', 'production', 'test', 'provision')
.default('development'),
PORT: Joi.number().default(3000),
}),
validationOptions: {
allowUnknown: false,
abortEarly: true,
},
}),
],
})
export class AppModule {}
它将在
节点_ENV
和端口上运行验证。当然,您可以将其扩展到更多的验证。然后你就可以有一个ConfigModule
,它有更小的配置服务,可以将每个段分割开来,这样所有的验证都会在启动时运行,并且在每个模块的上下文中只有你需要的东西可用。嘿,非常感谢你的回复。我在寻找一种方法,在server.config.service.ts中进行我的joi验证,在database.config.service.ts中进行另一个joi验证。你会怎么做?只需在每个服务的构造函数中调用它?我认为这将是一种更干净的方法,因为每个配置都可以自我验证,自定义配置模块不必知道所有这些字段……如果您想要单独的验证,那么每次验证都需要一个Joi模式,并且需要在构造函数(或从构造函数调用的方法)中运行验证每项服务的费用。老实说,由于验证可能相当繁重,我想说,在启动时,在同一个地方把它放在一边是比较可取的,因为它可以让所有东西都保持在一起。那是我的两分钱