Skip to content

Instantly share code, notes, and snippets.

@ahmadarif
Created October 17, 2019 10:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmadarif/b25c70000e921549fbaa35c264501dc0 to your computer and use it in GitHub Desktop.
Save ahmadarif/b25c70000e921549fbaa35c264501dc0 to your computer and use it in GitHub Desktop.
Config Module
import { Module } from '@nestjs/common';
import { ConfigService } from './config.service';
@Module({
providers: [
{
provide: ConfigService,
useValue: new ConfigService('.env'),
},
],
exports: [ConfigService],
})
export class ConfigModule {}
import { Injectable, Logger } from '@nestjs/common';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
dotenv.config();
@Injectable()
export class ConfigService {
private readonly envConfig: { [key: string]: string };
constructor(filePath: string) {
try {
this.envConfig = dotenv.parse(fs.readFileSync(filePath));
} catch (e) {
Logger.warn(`File ${filePath} not found, app will use process.env`);
}
}
get(key: string): string {
return this.envConfig[key];
}
getInt(key: string): number {
return parseInt(this.envConfig[key], 10);
}
getBoolean(key: string): boolean {
return this.envConfig[key] === 'true';
}
getObject<T>(key: string): T {
try {
return JSON.parse(this.envConfig[key]) as T;
} catch (e) {
return null;
}
}
getArray(key: string): string[] {
if (!this.envConfig[key]) {
return [];
}
try {
return this.envConfig[key].split(',');
} catch (e) {
return [];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment