forked from irandeno/coffee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
68 lines (57 loc) · 1.6 KB
/
mod.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
59
60
61
62
63
64
65
66
67
68
import Validateable from "./src/Validateable.ts";
import lensProp from "./src/lensProp.ts";
interface Configs {
[key: string]: unknown;
}
interface Parser {
(raw: string): Configs;
}
type LoadOptions = {
configPath?: string;
};
interface RuntimeAPI {
getEnvVar(key: string): string | undefined;
getEnvVars(): Configs;
readFile(path: string): string;
}
class DenoAPI implements RuntimeAPI {
getEnvVars() {
return Deno.env.toObject();
}
getEnvVar(key: string) {
return Deno.env.get(key);
}
readFile(path: string) {
return Deno.readTextFileSync(path);
}
}
export class Coffee {
defaultOptions: LoadOptions = { configPath: "./config" };
runtimeAPI: RuntimeAPI = new DenoAPI();
private isLoaded = false;
parsers: { [k: string]: Parser } = {
JSON: (t: string) => JSON.parse(t),
};
configs: Configs = {};
load(options: LoadOptions = this.defaultOptions): void {
const rawConfigs = this.runtimeAPI.readFile(
options.configPath + "/default.json",
);
this.configs = this.parsers.JSON(rawConfigs);
const environment = this.runtimeAPI.getEnvVar("DENO_ENV");
if (typeof environment !== "undefined") {
const rawEnvConfig = this.runtimeAPI.readFile(
options.configPath + `/${environment}.json`,
);
const envParsedConfig = this.parsers.JSON(rawEnvConfig);
Object.assign(this.configs, envParsedConfig);
}
this.isLoaded = true;
}
get(path: string): Validateable {
if (this.isLoaded === false) this.load();
const v = lensProp(this.configs, path);
return new Validateable(v);
}
}
export default new Coffee();