This repository has been archived by the owner on Jan 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
162 lines (143 loc) · 4.01 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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
'use strict';
const path = require('path');
const fs = require('fs');
const isObject = require('lodash/fp/isObject');
const template = require('lodash/fp/template');
const merge = require('lodash/fp/merge');
const get = require('lodash/fp/result');
const omit = require('lodash/fp/omit');
const logger = require('logtown')('easy-loader');
//
// Usage:
//
// 1. const config = require('easy-loader');
// console.log(config('database.username'));
//
// 2. const config = require('easy-loader')({ pattern: 'configs/<%=NODE_ENV%>.js' })
// console.log(config('database.password'));
//
// Loading process:
//
// 1. NODE_ENV = development
// [exists] default.js
// [exists] development.js
//
// <= merge(development.js, default.js)
//
// 2. NODE_ENV = development
// [exists] default.js
// [NOT exists] development.js
//
// <= content(default.js)
//
// 3. NODE_ENV = development
// [NOT exists] default.js
// [NOT exists] development.js
//
// <= throw Error('At least one file MUST exists')
//
// 4. NODE_ENV = development
// [NOT exists] default.js
// [exists] development.js
//
// <= content(development.js)
//
function isAbsolutePath(p) {
return path.resolve(p) === path.normalize(p);
}
const exists = (path) => {
try {
fs.accessSync(path);
return true;
} catch (e) {
return false;
}
};
/**
* @param {Function} compiledPattern
* @param {string} cwd
* @param {{}} variables
* @return {string}
*/
function buildPath(compiledPattern, cwd, variables) {
let configPath = compiledPattern(Object.assign({}, process.env, variables));
if (!isAbsolutePath(configPath)) {
configPath = path.join(cwd, configPath);
}
return configPath;
}
/**
* @param variable
* @return {[*]}
*/
function getArray(variable) {
return Array.isArray(variable) ? variable : [variable];
}
/**
* @param {[]} patterns
* @param {{}} patternVars
* @param {string} cwd
*/
function findConfigPath(patterns, patternVars, cwd) {
return patterns
.map((pattern) => template(pattern))
.map((compiled) => (variables) => buildPath(compiled, cwd, variables))
.map((compiledPartial) => {
try {
return compiledPartial(patternVars);
} catch (e) {
logger.warn(e);
return false;
}
})
.filter((compiledPath) => compiledPath && exists(compiledPath))
.reduce((acc, item) => {
if (!acc) {
acc = item;
}
return acc;
}, '')
}
function buildConfigFunction({
pattern = ['config/<%=NODE_ENV%>.js', 'configs/<%=NODE_ENV%>.js', '<%=NODE_ENV%>.js'],
patternVars = { NODE_ENV: process.env.NODE_ENV || 'development' },
patternDefaultVars = { NODE_ENV: 'default' },
cwd = process.cwd(),
useRC = true,
rcOpts = { prefix: 'local' },
mergeWithDefaults = true,
} = {}) {
let result = {};
const patterns = getArray(pattern);
const configPath = findConfigPath(patterns, patternVars, cwd);
const configDefaultPath = findConfigPath(patterns, patternDefaultVars, cwd);
if (!configPath && !configDefaultPath) {
throw new Error('At least one config file MUST exists');
}
if (mergeWithDefaults && configDefaultPath) {
result = merge(result, require(configDefaultPath));
}
if (configPath) {
result = merge(result, require(configPath));
}
if (useRC) {
// result will be mutated by rc internals
const rcConfig = require('rc')(rcOpts.prefix, {}, {});
result = merge(result, omit(['config', 'configs'], rcConfig));
}
let resultFn = (key, defaultValue) => {
const val = get(key, result);
if (typeof val === 'undefined') {
return defaultValue;
}
return val;
};
return Object.assign(resultFn, result);
}
module.exports = (...args) => {
if (isObject(args[0])) {
return buildConfigFunction(args[0]);
}
const conf = buildConfigFunction();
return conf(...args);
};