NestJS 装饰配置
说明
环境变量配置模块 (原始内容存档于2019-09-21) (英语). Nest.js 使用 类验证器 作装饰.
安装
$ npm i @applifting-io/nestjs-decorated-config
使用量
假设您有以下 .env 文件( 或者在提供这些变量的环境中启动您的应用程序)
SECRET="WmOZI77oOQf76cM9GASDWB7tS3MZ01TPM395FCUN9oE="
URL="http://localhost:3000"
配置服务定义
创建自己的配置服务 。 为每个环境变量定义属性。 用 @ Env 装饰器装饰它们 - 确保第一个参数符合您的环境变量名称 .
可选地用类验证器装饰您的属性.
// config.service.ts
import { Env } from '@applifting-io/nestjs-decorated-config';
import { Injectable } from '@nestjs/common';
import { IsNotEmpty, IsUrl } from 'class-validator';
@Injectable()
export class ConfigService {
@Env('URL')
@IsUrl()
readonly url: string;
@Env('SECRET')
@IsNotEmpty()
readonly secret: string;
@Env('BOOLEAN_VAR', {
defaultValue: true, // will use true if no other value is populated from environment
})
readonly booleanVar: boolean;
@Env('ARRAY_VAR', {
delimiter: '|', // will use comma as a delimiter for the array ("," is the default delimiter)
parseArray: true, // will parse the array from string to array of strings
})
readonly arrayVar: string[];
@Env('NUMBER_VAR', {
defaultValue: 42, // will use 42 if no other value is populated from environment
})
readonly numberVar: number;
@Env('JSON_VAR', {
parseJson: true, // will parse stringified JSON object
})
readonly jsonVar: {
key: string;
};
@Env('EXPOSED_VAR', {
expose: true, // will print the value of this variable in the console on startup
})
readonly exposedVar: string;
}
选项
@ Env 选择预期 EnvDecoratorOptions 作为第二个参数:
type EnvDecoratorOptions<T = any> = {
/**
* Variable's default value, used if no other value is populated from environment. Undefined by default
*/
defaultValue?: T | (() => T);
/**
* Exposing will show the value of variable in log. False by default
*/
expose?: boolean;
/**
* Removes last string character, if it is a forward slash. False by default
*/
removeTrailingSlash?: boolean;
/**
* Parses the value to a JavaScript object with JSON.parse. Throws on invalid input. False by default
*/
parseJson?: boolean;
};
配置模块初始化
导入并添加 CfigMudule 到导入您的根模块的数组 .
// app.module.ts
import { ConfigModule } from '@applifting-io/nestjs-decorated-config';
import { Module } from '@nestjs/common';
import { ConfigService } from 'config.service.ts';
@Module({
imports: [ConfigModule.forRootAsync(ConfigService)],
})
export class AppModule {}
选项
CfigMudule. for RootAsync 可选预期 ConfigModuleOptions 作为第二个参数:
type ConfigModuleOptions = {
/**
* Print all variables with `expose: true`. False by default
*/
printOnStartup?: boolean;
/**
* Validate all variables using class-validator decorators. True by default
*/
validate?: boolean;
};
需要时注入配置
全球都有配置服务,像其他供应商一样注入
// example.service.ts
@Injectable()
export class ExampleService {
constructor(private readonly config: ConfigService) {}
example() {
console.log(config.url); // => 'http://localhost:3000'
console.log(config.secret); // => 'WmOZI77oOQf76cM9GASDWB7tS3MZ01TPM395FCUN9oE='
console.log(config.booleanVar); // => true
console.log(config.arrayVar); // => ['value1', 'value2']
console.log(config.numberVar); // => 42
console.log(config.jsonVar); // => { key: 'value' }
console.log(config.exposedVar); // => 'value'
}
}
重要
重要性 如果使用.env文件 :
Env装饰者从process.env。由于 TS 中装饰器的性质,您需要确保从.env 文件装入变量 在此之前 导入Env或本身进口的任何其他联署材料模块Env。 。 。 .
在实践中实现这一点的一个方法是运行 Dotenv , 然后在主.ts 切入点中动态导入您的其余应用程序
// main.ts
import * as dotenv from 'dotenv';
// Dotenv needs to run before importing bootstrap, because @Env decorators are
// executed when JS interpreter interprets the decorated class which is in
// bootstrap's import tree, and we need env var resolution to be finished before that
dotenv.config();
import('./bootstrap').then(({ bootstrap }) => bootstrap());