-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
70 lines (61 loc) · 1.76 KB
/
index.js
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
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const yaml = require('js-yaml');
const configsDir = path.normalize(path.join(process.env.PWD, 'static-store'));
class StaticStoreModule {
constructor(configPath) {
this._configPath = configPath;
}
get(name) {
return this.getOrDefault(name, undefined);
}
getOrFail(name) {
const result = this[name];
if (result === undefined) {
throw new Error(`Key ${name} not found in ${this._configPath}`);
}
return result;
}
getOrDefault(name, defaultValue) {
const result = this[name];
if (result === undefined) {
return defaultValue;
}
return result;
}
}
function loadObjectForProp(name) {
const kebabName = _.kebabCase(name);
const configPath = getConfigPath(kebabName);
if (!fs.existsSync(configPath)) {
throw new Error(`No configuration for ${name} (${configPath})`);
}
const fileContents = fs.readFileSync(configPath, {encoding: 'utf-8'});
const yamlContent = yaml.safeLoad(fileContents);
const result = Object.assign(new StaticStoreModule(configPath), yamlContent);
return Object.freeze(result); // TODO deeply freeze it for bonus points
}
function getConfigPath(filename) {
return path.join(configsDir, `${filename}.yaml`);
}
/**
* An object which will contain a representation of the files in the directory
* `other-config`.
*
* Example use: require('./static-store').iceCreamFlavor[1] // returns 'VANILLA'
*
* The above example will look for the file
* `static-store/ice-cream-flavor.yaml`.
*
* Results are cached.
*/
const StaticStore = new Proxy({}, {
get: (target, name) => {
if (!this[name]) {
this[name] = loadObjectForProp(name);
}
return this[name];
}
});
module.exports = StaticStore;