@shakajs/nestjs-config
v2.1.1
Published
Config module for NestJS applications
Downloads
156
Readme
Install
npm i @shakajs/nestjs-config --save
Using
1. Create config file:
import { ConfigDefaultValue } from '@shakajs/nestjs-config';
export class AppConfig {
@ConfigDefaultValue(() => process.env.DB_HOST || 'localhost')
dbHost: string;
@ConfigDefaultValue(() => process.env.DB_PORT || '3306')
dbPort: string;
@ConfigDefaultValue(() => process.env.DB_USER || 'root')
dbUser: string;
@ConfigDefaultValue(() => process.env.DB_PASSWORD || '')
dbPassword: string;
@ConfigDefaultValue(() => process.env.TOKEN || '')
token: string;
}
Note: if you have .env it values will be loaded automatically.
2. Register created config in root-module:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@shakajs/nestjs-config';
import { AppConfig } from './app.config';
@Module({
imports: [
ConfigModule.register({ schemas: [AppConfig] }),
],
})
export class AppModule {}
3. Use in service:
import { Injectable } from '@nestjs/common';
import { AppConfig } from '../app.config';
import { InjectConfig } from '@shakajs/nestjs-config';
@Injectable()
export class ExampleService {
constructor(
@InjectConfig() private readonly config: AppConfig,
) {
}
getTokenFromCongig() {
return this.config.token;
}
}
4. Use in custom provider:
import { APP_CONFIG } from '@shakajs/nestjs-config';
...
providers: [
{
provide: 'SOME_VALUE',
useFactory: (config: AppConfig) => {
return config.someKey;
},
inject: [APP_CONFIG],
}
],