-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathboot.store.ts
79 lines (69 loc) · 2.33 KB
/
boot.store.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
69
70
71
72
73
74
75
76
77
78
79
import { get, isString, isArray, isObject } from 'lodash';
import { objectToMap } from '@nestcloud/common';
import { compile } from 'handlebars';
export class BootStore {
private _data: any;
private readonly _map: { [key: string]: any } = {};
private readonly watchRefs: {
[key: string]: Array<(value: any) => void>;
} = {};
private readonly defined: { [key: string]: boolean } = {};
public get data() {
return this._data;
}
public set data(data: any) {
this._data = data;
if (isObject(this._data)) {
for (const key in this._data) {
if (this._data.hasOwnProperty(key)) {
this.compileWithEnv(key, this._data, this._data[key]);
}
}
}
this.updateConfigMap();
}
public merge(data: any) {
}
public get<T extends any>(path?: string, defaults?: T): T {
if (!path) {
return this._data;
}
return get(this._data, path, defaults);
}
public watch(path: string, ref: (value: any) => void) {
if (!this.watchRefs[path]) {
this.watchRefs[path] = [];
}
this.watchRefs[path].push(ref);
if (!this.defined[path]) {
Object.defineProperty(this._map, path, {
set: newVal => {
this.watchRefs[path].forEach(ref => ref(newVal));
},
});
this.defined[path] = true;
}
}
private compileWithEnv(key: string | number, parent: any, config: any) {
if (isString(config)) {
const template = compile(config.replace(/\${{/g, '{{'));
parent[key] = template({ ...process.env, ...this._data });
} else if (isArray(config)) {
config.forEach((item, index) => this.compileWithEnv(index, config, item));
} else if (isObject(config)) {
for (const key in config) {
if (config.hasOwnProperty(key)) {
this.compileWithEnv(key, config, config[key]);
}
}
}
}
private updateConfigMap() {
const configMap = objectToMap(this._data);
for (const key in configMap) {
if (this._map[key] !== configMap[key]) {
this._map[key] = configMap[key];
}
}
}
}