@sdu-turing/config
@sdu-turing/config, another way to config Environment Variables in Nest.JS.
Usage
Installation
$ npm i @sdu-turing/config
# used for environment variables schema validation
$ npm i class-validator class-transformer
Examples
First, create config/user.config.ts
// config/user.config.ts
import { Env } from '@sdu-turing/config';
import { IsEnum, IsString, IsUrl } from 'class-validator';
export class UserConfigSchema {
@IsEnum(NodeEnvironment)
NODE_ENV: NodeEnvironment;
@IsString()
MONGO_URI: string;
@IsString()
TURING_APP_ID: string;
@IsUrl()
OAUTH_SERVICE_URL: string;
// ...
}
export class UserConfig {
mongoUri: string;
constructor(@Env() env: UserConfigSchema) {
this.mongoUri = env.MONGO_URI;
}
}
optional, create .env
file, or just use process.env.
# .env
MONGO_URI=mongodb://....
....
register ConfigModule
in AppModule
:
@Module({
imports: [
ConfigModule.forRoot({
schemas: [UserConfigSchema], // the schemas
configs: [UserConfig], // register provider as global
}),
],
})
export class AppModule {}
Usage
ConfigModule.forRoot({
// [optional] load .env file? default: `true`
loadDotEnv: true,
// [optional] the schema you want to validate for environment variables
schemas: [],
// [optional] the string to throw if an error occurs in validation
validationErrorMessage: '' | (errors: ValidationError[]) => string,
// [optional] cache process.env to improve performance, default false
useCache: false,
// [optional] these configs are registered as global providers
// or use ConfigModule.forFeature(configs) in scope,
configs: []
})
In a provider, a ConfigService or UserConfig, use @Env()
to inject the process.env(or cache).
class ConfigService {
@Env()
env: EnvironmentVariables;
}