-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.ts
58 lines (48 loc) · 1.43 KB
/
config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { Module, Global } from "@nestjs/common";
import * as dotenv from "dotenv";
import * as fs from "fs";
import { Env, parseEnv } from "./common";
export class ConfigService {
public static fromFile(filePath: string): ConfigService {
const envConfig = dotenv.parse(fs.readFileSync(filePath));
return new ConfigService(envConfig);
}
/**
* In tests, an _empty_ config will be generated. Tests will have to
* fake the calls to various config values, just like they'd do for
* other dependencies.
*/
public static forTesting(): ConfigService {
return new ConfigService({});
}
private readonly envConfig: { [prop: string]: string };
constructor(envConfig?: { [prop: string]: string }) {
this.envConfig = envConfig || {};
}
public get env(): Env {
// tslint:disable:no-string-literal
return parseEnv(this.envConfig["ENV"]);
}
public get port(): number {
// tslint:disable:no-string-literal
return parseInt(this.envConfig["PORT"], 10);
}
}
@Global()
@Module({
providers: [{
provide: ConfigService,
useValue: ConfigService.fromFile(".env"),
}],
exports: [ConfigService],
})
export class ConfigModule { }
@Global()
@Module({
providers: [{
provide: ConfigService,
useValue: ConfigService.forTesting(),
}],
exports: [ConfigService],
})
export class ConfigTestingModule { }