@libs-for-dev/nestjs-config-module
v1.0.1
Published
NestJS config module with config validation
Downloads
220
Readme
NestJS Config module
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.
Installation
yarn add @libs-for-dev/nestjs-config-module
Usage
Prepare config and config validator
- 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
}
}
Use with valid config
- 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
Use with invalid config
- 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
Usage with env variables
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 {}