@libs-for-dev/nestjs-config-module
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

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

  1. create config validator class
import { Expose } from 'class-transformer'
import { IsNumber, IsString } from 'class-validator'

export class ExampleConfigValidator {
  @IsNumber()
  @Expose()
  public keyNumber!: number
}
  1. 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

  1. 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 {}
  1. run application and get validated config
const app = await NestFactory.create(ExampleModule)

console.log(app.get(ExampleConfig).getKeyNumber())
// 1

Use with invalid config

  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 {}
  1. 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 {}

Dependents (0)

Package Sidebar

Install

npm i @libs-for-dev/nestjs-config-module

Weekly Downloads

167

Version

1.0.1

License

MIT

Unpacked Size

10.5 kB

Total Files

14

Last publish

Collaborators

  • uwl