/
index.js
54 lines (45 loc) · 1.24 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
function toUnderscore(str) {
return str.replace(/(ID|URL|[A-Z])/g, function($1){return "_"+$1.toLowerCase();});
};
function getEnvKey(prefix, configKey) {
if (prefix && prefix !== '') {
return prefix + '_' + toUnderscore(configKey).toUpperCase();
}
return toUnderscore(configKey).toUpperCase();
}
function convertType(defaultValue, valueStr) {
switch (typeof defaultValue) {
case 'string':
return valueStr;
case 'number':
if (Number.isInteger(defaultValue)) {
return parseInt(valueStr);
}
return parseFloat(valueStr);
case 'boolean':
if (valueStr === 'true' || valueStr === 'yes') {
return true;
}
return false;
default:
return valueStr;
}
}
var exports = module.exports = function(defaultConfig, options) {
var config = {};
var prefix = '';
if (options && options.prefix) {
prefix = toUnderscore(options.prefix).toUpperCase();
}
for (var configKey in defaultConfig) {
if (defaultConfig.hasOwnProperty(configKey)) {
var envConfig = process.env[getEnvKey(prefix, configKey)];
if (envConfig) {
config[configKey] = convertType(defaultConfig[configKey], envConfig);
} else {
config[configKey] = defaultConfig[configKey];
}
}
}
return config;
}