Created
October 17, 2019 10:16
-
-
Save ahmadarif/b25c70000e921549fbaa35c264501dc0 to your computer and use it in GitHub Desktop.
Config Module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Module } from '@nestjs/common'; | |
import { ConfigService } from './config.service'; | |
@Module({ | |
providers: [ | |
{ | |
provide: ConfigService, | |
useValue: new ConfigService('.env'), | |
}, | |
], | |
exports: [ConfigService], | |
}) | |
export class ConfigModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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