-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (41 loc) · 1.77 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
'use strict';
class Config {
constructor(_config) {
this.config = _config ? _config : {};
this.config.envPrefix = this.config.envPrefix || '';
this.config.prefix = this.config.prefix ||this.config.envPrefix;
this.config.defaults = this.config.defaults && Object.keys(this.config.defaults).length !== 0 ? this.config.defaults : {}
}
get(name,inlineDefault){
const lookForValue = path => path.split('.').reduce( (accumulator,name) => accumulator ? accumulator[name] : null, this.config.defaults);
const lookInEnv = name => process.env[`${this.config.prefix}${name.replace(/([^a-zA-Z0-9_])/g,'_')}`];
const exists = value => value !== undefined && value !== null;
const get = (name,inlineDefault) => {
let value = lookInEnv(name)
if(!exists(value)) value = lookForValue(name)
if(!exists(value)) value = inlineDefault
return value;
};
const isObject = value => typeof value === 'object';
const objEnvOverride = (name,value) => {
if(isObject(value)){
Object.keys(value).forEach( key => {
if(isObject(value[key])){
objEnvOverride(`${name}.${key}`,value[key]);
} else {
value[key] = lookInEnv(`${name}.${key}`) || value[key]
}
})
}
return value;
};
return objEnvOverride( name, get(name,inlineDefault) );
}
update(source){
Object.keys(source).forEach( key => this.config.defaults[key] && typeof this.config.defaults[key] === 'object' ? deepCopy(this.config.defaults[key],source[key]) : this.config.defaults[key] = source[key] );
}
child(name) {
return new Config({prefix:`${this.config.prefix}${this.config.prefix ? '_' : ''}${name}`,defaults:this.get(name) });
}
}
module.exports = Config;