It is config module with validation values in runtime.
It does not allow to run application with invalid configuration.
Use class-validator
validators before apply in application.
yarn add @libs-for-dev/nestjs-config-module
- create config validator class
import { Expose } from 'class-transformer'
import { IsNumber, IsString } from 'class-validator'
export class ExampleConfigValidator {
@IsNumber()
@Expose()
public keyNumber!: number
}
- create config class
import { Inject, Injectable } from '@nestjs/common'
import { ExampleConfigValidator } from './example-config.validator'
@Injectable()
export class ExampleConfig {
public constructor(@Inject(ExampleConfigValidator) private readonly validator: ExampleConfigValidator) {}
public getKeyNumber(): number {
return this.validator.keyNumber
}
}
- init module with validation config. Provide raw config from
process.env
import { ExampleConfigValidator } from './example-config'
import { ExampleConfig } from './example-config.validator'
const config = { keyNumber: 1 }
@Module({
imports: [
ConfigsModule.forFeature([ExampleConfig], [ExampleConfigValidator], config),
]
})
export class ExampleModule {}
- run application and get validated config
const app = await NestFactory.create(ExampleModule)
console.log(app.get(ExampleConfig).getKeyNumber())
// 1
- init module with validation config. Provide raw config from
process.env
import { ExampleConfigValidator } from './example-config'
import { ExampleConfig } from './example-config.validator'
// no expected in ExampleConfigValidator key
// const config = { }
// or wrong excepced for validation value
const config = { keyNumber: "not a number" }
@Module({
imports: [
ConfigsModule.forFeature([ExampleConfig], [ExampleConfigValidator], config),
]
})
export class ExampleModule {}
- run application and get validated config
const app = await NestFactory.create(ExampleModule)
// throws error before run application
import * as process from 'process'
import { ExampleConfigValidator } from './example-config'
import { ExampleConfig } from './example-config.validator'
@Module({
imports: [
ConfigsModule.forFeature(
[ExampleConfig],
[ExampleConfigValidator],
process.env
),
]
})
export class ExampleModule {}