-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
190 lines (144 loc) · 4.64 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
const fs = require('fs')
const path = require('path')
const dotenv = require('./dotenv.js')
const yaml = require('js-yaml')
const deepmerge = require('deepmerge')
//-----------------------------------------------------------------
const default_fileList = [
'config/config.json',
'config/config.yml',
'conf/config.json',
'conf/config.yml',
//'conf/config.development.yml', // auto load
'config.json',
'config.yml',
'config.env',
'.env'
];
const default_options = {
export: true, // 직접 env에 export
force: false // export 할때 기존에 값이 있어도 강제로 쓰기
};
const env_list = [
'production',
'prod',
'development',
'devel',
'test'
]
function putEnvValue(key, value, cache, options) {
if (options.force != true) {
// 실행전 ENV에 등록된 거면 무시 (보통 Cross-env에서 셋팅된 것이나 컨테이너에서 부여한 것)
if (process.env[key]) {
if (cache[key] == undefined) return;
}
}
if (typeof(value) != 'object') {
if (options.export)
process.env[key.toUpperCase()] = value;
cache[key] = value;
} else
cache[key] = (cache[key] == undefined) ? value : Object.assign(cache[key], value);
}
function loadFileJSON(filepath, cache, options) {
const configs = JSON.parse(fs.readFileSync(filepath, {encoding:'utf8'}));
Object.keys(configs).forEach( key=>{ putEnvValue(key, configs[key], cache, options) });
return filepath;
}
function loadFileENV(filepath, cache, options) {
const configs = dotenv.parse(fs.readFileSync(filepath, { encoding: 'utf8' }));
Object.keys(configs).forEach( key=>{ putEnvValue(key, configs[key], cache, options) });
return filepath;
}
function loadFileYML(filepath, cache, options) {
const configs = yaml.safeLoad(fs.readFileSync(filepath, 'utf8'));
Object.keys(configs).forEach( key=>{ putEnvValue(key, configs[key], cache, options) });
return filepath;
}
function resolveFiles(file_list) {
let loadTarget = [];
file_list = file_list.map(i => path.resolve(process.cwd(), i)).filter(i => fs.existsSync(i))
// 디렉토리로 지정된 경우 안에 있는 리스트 뽑기
file_list.forEach(file => {
if (fs.lstatSync(file).isDirectory()) {
let subList = fs.readdirSync(file)
subList.sort( (a,b)=> (a.length - b.length))
subList.forEach(subItem=> {
if (fs.lstatSync(file+'/'+subItem).isFile())
loadTarget.push( path.resolve(process.cwd(), file+"/"+subItem) );
})
} else
loadTarget.push(file);
})
let env = (process.env.NODE_ENV) ? process.env.NODE_ENV : false;
// 로딩될 필요 없는 녀석들 제거
loadTarget = loadTarget.filter(file => {
let flag = (file.indexOf('example.') > -1) || (file[0] == "_");
env_list.forEach(v => {
if (v == env) return;
flag = flag || (file.indexOf(v+'.') > -1)
})
return !flag;
})
return loadTarget;
}
function getValue(data, path, defValue) {
let p = path.split(".");
let t = data;
for (let i=0; i < p.length; i++) {
if (t == undefined) break;
t = t[p[i]];
}
if (t == undefined)
t = defValue;
return t;
}
// ------------------------------------------------
// 불러올 파일을 순서대로 정한다. 이왕이면 명시적인게 좋다.
function configInit(loadFileList, options) {
if (Array.isArray(loadFileList) == false) {
options = loadFileList;
loadFileList = undefined;
}
options = Object.assign(default_options, (options) ? options : {});
loadFileList = (loadFileList) ? loadFileList : default_fileList;
let cached = {};
let loadedFiles = [];
resolveFiles(loadFileList).forEach(file=>{
let ext = path.extname(file);
if (ext.toLowerCase() == '.json')
loadedFiles.push( loadFileJSON(file, cached, options) );
if (ext.toLowerCase() == '.yaml' || ext.toLowerCase() == '.yml')
loadedFiles.push( loadFileYML(file, cached, options) );
if (ext.toLowerCase() == '') {
let p = path.parse(file);
if (p.name == '.env') {
loadedFiles.push( loadFileENV(file, cached, options) );
}
}
})
loadedFiles = loadedFiles.filter(i => i);
// overwrite new variabels over default object
if (options.defaults)
cached = deepmerge(options.defaults || {}, cached)
function config(path, defValue) {
let p = path.split(".");
let t = config;
for (let i=0; i < p.length; i++) {
if (t == undefined) break;
t = t[p[i]];
}
if (t == undefined) t = defValue;
return t;
}
for (let key in cached) {
config[key] = cached[key];
}
return {
order: loadedFiles,
values: cached,
store: getValue.bind(null, cached),
config
}
}
module.exports = configInit;