-
Notifications
You must be signed in to change notification settings - Fork 0
/
dotEnvLoader.ts
44 lines (40 loc) · 1.08 KB
/
dotEnvLoader.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
import { readFileSync } from 'fs'
import { DotEnvLoaderError } from './dotEnvLoaderError'
import { EnvLoader } from './envLoader'
import type { EnvMapper } from './envMappers/envMapper'
/**
* Loads configuration from .env files.
*/
export class DotEnvLoader<T = unknown> extends EnvLoader<T> {
/**
* Create a new instance of this loader.
*
* @param mapper Environment key mapper.
* @param filename Path to .env file.
* @param dotEnvParse parse() function from "dotenv".
*/
constructor(
mapper: EnvMapper,
private readonly filename: string,
private readonly dotEnvParse: typeof import('dotenv')['parse'],
) {
super(mapper)
}
/**
* Loads and parses configured .env file.
*/
protected loadEnv(): Record<string, unknown> {
try {
const source = readFileSync(this.filename, 'utf-8')
return this.dotEnvParse(source)
} catch (ex) {
throw new DotEnvLoaderError(this.filename, ex)
}
}
/**
* Returns configured filename as a source.
*/
protected getSource(): string | undefined {
return this.filename
}
}