Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
akupiec
GitHub Repository: akupiec/mad-proxy
Path: blob/master/src/config/config.js
115 views
1
const deepAssign = require('deep-assign');
2
const argv = require('./argv');
3
const path = require('path');
4
const LOGGER = require('./logger');
5
6
function loadConfigFile() {
7
const defaultConfig = require('../../bin/mad-proxy.config');
8
defaultConfig.proxies = [];
9
let configFileData;
10
if (argv.config) {
11
let fileName;
12
try {
13
fileName = path.normalize(process.cwd() + '/' + argv.config);
14
configFileData = require(fileName);
15
} catch (e) {
16
module.exports = argv;
17
LOGGER.fatal(`No config file ${fileName} was found, this will cause severe errors!!.`);
18
}
19
}
20
const config = deepAssign(defaultConfig, configFileData, argv);
21
return config;
22
}
23
24
function extendWithDefaultValues(config) {
25
if (config.proxies) {
26
config.proxies = config.proxies.map((proxyConf) => {
27
proxyConf.cache = proxyConf.cache || {enabled: false};
28
return proxyConf;
29
});
30
}
31
return config;
32
}
33
34
function validateConfig(config) {
35
let isValid = true;
36
if (!config.proxies) {
37
LOGGER.error('Invalid config file. Missing \'config.proxies\' array');
38
isValid = false;
39
}
40
41
config.proxies.map((proxyConf, idx) => {
42
if (!proxyConf.target) {
43
LOGGER.error(`Invalid config file. Missing 'config.proxies[${idx}].target' array`);
44
isValid = false;
45
}
46
if (!proxyConf.path) {
47
LOGGER.error(`Invalid config file. Missing 'config.proxies[${idx}].path' array`);
48
proxyConf.path = '';
49
isValid = false;
50
}
51
if (!proxyConf.path.match(/^\/.*/)) {
52
LOGGER.error(`Invalid config file. 'config.proxies[${idx}].path=${proxyConf.path}' have to START with slash '\\'`);
53
isValid = false;
54
}
55
if (proxyConf.path.match(/.+\/$|\*$/)) {
56
LOGGER.error(`Invalid config file. 'config.proxies[${idx}].path=${proxyConf.path}' shouldn't END with slash '\\' or asterisk '*', mad-proxy will add one for you.`);
57
isValid = false;
58
}
59
});
60
return isValid;
61
}
62
63
let config = loadConfigFile();
64
config = extendWithDefaultValues(config);
65
if(!validateConfig(config)) {
66
throw Error('Invalid config!');
67
}
68
69
LOGGER.logLvl = config.log;
70
module.exports = config;
71
72