/
gconf.js
103 lines (83 loc) · 2.58 KB
/
gconf.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/* jshint -W138 */
const _ = require('lodash');
const component_factory = require('./components/factory');
class GConf{
constructor(options){
this.modifier_queue = [];
this.provider = null;
this.meta = {
default_domain: 'default',
node_env: false
};
if(options){
this._registerOptions(options);
var meta_settings = options.gconf || {};
Object.assign(this.meta, meta_settings);
}
Object.seal(this);
}
get default_domain(){
if(this.meta.node_env)
return process.env.NODE_ENV || this.meta.default_domain;
return this.meta.default_domain;
}
_registerOptions(options){
let wrapped = _(Object.keys(options));
let providers = wrapped.intersection(component_factory.PROVIDERS);
let modifiers = wrapped.intersection(component_factory.MODIFIERS);
if(providers.size() > 1){
throw new Error('There can be only one provider currently');
} else if(providers.size() == 1){
let provider = providers.first();
this.registerProvider(provider, options[provider]);
}
modifiers.forEach((modifier) =>
this.registerModifier(modifier, options[modifier]));
}
registerProvider(provider, options){
this.provider = component_factory.createProvider(provider, options);
}
registerModifier(modifier, options){
let modifier_instance = component_factory.createModifier(modifier, options);
this.modifier_queue.push(modifier_instance);
}
get default(){
return{
get: this.request.bind(this, this.default_domain),
request: this.request.bind(this, this.default_domain),
requestMany: this.requestMany.bind(this, this.default_domain)
};
}
checkBeforeRequest(){
if(!this.provider){
throw new Error('No provider was registered');
}
}
get(domain, location){
if(location && Array.isArray(location)){
return this.requestMany(domain, location);
} else {
return this.request(domain, location);
}
}
request(domain, path){
domain = domain || this.default_domain;
this.checkBeforeRequest();
let baseConfig = this.provider.request(domain, path);
this.modifier_queue.forEach((modifier) => {
baseConfig = modifier.modify(baseConfig, path);
});
return baseConfig;
}
requestMany(domain, paths){
this.checkBeforeRequest();
var configs = this.provider.requestMany(domain, paths);
return configs.map((config, index) => {
this.modifier_queue.forEach(modifier => {
config = modifier.modify(config, paths[index]);
});
return config;
});
}
}
module.exports = GConf;