不熟悉 Angular,所以我不知道它是否直观,但您应该考虑使用 Dynamic Modules 来注入您的配置。
NestJS 文档中的示例已经非常接近您想要的,除了它们适用于直接在 ConfigService 中加载的不同 .env 文件。
您的案例需要一些编码,但您只需执行一次,然后可以在任何其他 NestJS 项目中重复使用。查看文档,您可以派生由ConfigModule.register() 服务的Injectable() 提供程序,它基于process.env.NODE_ENV 是适当环境类的一个实例。
或者您当然可以使用直接加载.env 的开箱即用示例。但这不是强类型的。
我个人使用基于 Joi 的 Schema Validation 和 Configuration Namespaces 并且还为配置设置定义了一个接口。像下面的示例代码:
env.schema.ts:
export const envSchema = Joi.object({
NODE_ENV: Joi.string()
.valid('development', 'production')
.default('development'),
EMAIL_VERIFICATION_SECRET: Joi.string().when('NODE_ENV', {
is: 'production',
then: Joi.required(),
otherwise: Joi.optional().default('the_email_verification_secret'),
}),
});
email.config.ts:
interface EmailConfig {
verificationSecret: string;
}
export default registerAs('email', (): EmailConfig => ({
verificationSecret: process.env.EMAIL_VERIFICATION_SECRET,
}));
notification.module.ts:
@Module({
imports: [
ConfigModule.forFeature(emailConfig),
],
})
export class NotificationModule {}
email-notification.service.ts:
@Injectable()
export class EmailNotificationService {
private secret: string;
constructor(
@Inject(emailConfig.KEY)
private mailConfig: ConfigType<typeof emailConfig>,
) {
this.secret = this.mailConfig.verificationSecret;
}
}
当然,您不必使用配置命名空间,但它会将配置分解为您在特定模块中所需的块。通过接口进行强类型化,并且使用Joi,您的架构既可以验证也可以适应适当的环境。