enigma-bbs/core/config_loader.js

235 lines
7.2 KiB
JavaScript
Raw Normal View History

2020-06-11 01:15:49 +00:00
// deps
const paths = require('path');
const async = require('async');
const moment = require('moment');
2020-06-11 01:15:49 +00:00
const _ = require('lodash');
2020-06-12 03:38:33 +00:00
const mapValuesDeep = require('deepdash/getMapValuesDeep')(_);
2020-06-11 01:15:49 +00:00
module.exports = class ConfigLoader {
constructor(
{ hotReload = true, defaultConfig = {}, defaultsCustomizer = null } = { hotReload : true, defaultConfig : {}, defaultsCustomizer : null } )
{
2020-06-11 01:15:49 +00:00
this.current = {};
this.hotReload = hotReload;
this.defaultConfig = defaultConfig;
this.defaultsCustomizer = defaultsCustomizer;
2020-06-11 01:15:49 +00:00
}
init(baseConfigPath, cb) {
this.baseConfigPath = baseConfigPath;
return this._reload(baseConfigPath, cb);
2020-06-11 01:15:49 +00:00
}
get() {
return this.current;
}
_reload(baseConfigPath, cb) {
let defaultConfig;
if (_.isFunction(this.defaultConfig)) {
defaultConfig = this.defaultConfig();
} else if (_.isObject(this.defaultConfig)) {
defaultConfig = this.defaultConfig;
} else {
defaultConfig = {};
}
//
// 1 - Fetch base configuration from |baseConfigPath|
// 2 - Merge with |defaultConfig|
// 3 - Resolve any includes
// 4 - Resolve @reference and @environment
// 5 - Perform any validation
//
async.waterfall(
[
(callback) => {
return this._loadConfigFile(baseConfigPath, callback);
},
(config, callback) => {
if (_.isFunction(this.defaultsCustomizer)) {
const stack = [];
const mergedConfig = _.mergeWith(
defaultConfig,
config,
(defaultVal, configVal, key, target, source) => {
var path;
while (true) { // eslint-disable-line no-constant-condition
if (!stack.length) {
stack.push({source, path : []});
}
const prev = stack[stack.length - 1];
if (source === prev.source) {
path = prev.path.concat(key);
stack.push({source : configVal, path});
break;
}
stack.pop();
}
path = path.join('.');
return this.defaultsCustomizer(defaultVal, configVal, key, path);
}
);
return callback(null, mergedConfig);
}
return callback(null, _.merge(defaultConfig, config));
},
(config, callback) => {
const configRoot = paths.dirname(baseConfigPath);
return this._resolveIncludes(configRoot, config, callback);
},
(config, callback) => {
config = this._resolveAtSpecs(config);
return callback(null, config);
},
],
(err, config) => {
if (!err) {
this.current = config;
}
return cb(err);
}
);
}
2020-06-11 01:15:49 +00:00
_convertTo(value, type) {
switch (type) {
case 'bool' :
case 'boolean' :
value = 'true' === value.toLowerCase();
break;
case 'number' :
{
const num = parseInt(value);
if (!isNaN(num)) {
value = num;
}
}
break;
case 'object' :
try {
value = JSON.parse(value);
} catch(e) {
// ignored
}
2020-06-11 01:15:49 +00:00
break;
case 'date' :
case 'time' :
case 'datetime' :
case 'timestamp' :
{
const m = moment(value);
if (m.isValid()) {
value = m;
}
}
break;
case 'regex' :
// :TODO: What flags to use, etc.?
break;
}
return value;
}
_resolveEnvironmentVariable(spec) {
const [, varName, type, array] = spec.split(':');
2020-06-11 01:15:49 +00:00
if (!varName) {
return;
}
let value = process.env[varName];
if (!value) {
return;
}
if ('array' === array) {
value = value.split(',').map(v => this._convertTo(v, type));
} else {
value = this._convertTo(value, type);
}
return value;
}
_loadConfigFile(filePath, cb) {
const ConfigCache = require('./config_cache');
const options = {
filePath,
hotReload : this.hotReload,
callback : this._configFileChanged.bind(this),
};
ConfigCache.getConfigWithOptions(options, (err, config) => {
return cb(err, config);
});
}
_configFileChanged({fileName, fileRoot}) {
2020-06-11 01:15:49 +00:00
const reCachedPath = paths.join(fileRoot, fileName);
if (this.configPaths.includes(reCachedPath)) {
this._reload(this.baseConfigPath, err => {
if (!err) {
const Events = require('./events.js');
Events.emit(Events.getSystemEvents().ConfigChanged);
}
});
}
2020-06-11 01:15:49 +00:00
}
_resolveIncludes(configRoot, config, cb) {
if (!Array.isArray(config.includes)) {
return cb(null, config);
}
// If a included file is changed, we need to re-cache, so this
// must be tracked...
const includePaths = config.includes.map(inc => paths.join(configRoot, inc));
async.eachSeries(includePaths, (includePath, nextIncludePath) => {
this._loadConfigFile(includePath, (err, includedConfig) => {
if (err) {
return nextIncludePath(err);
}
_.defaultsDeep(config, includedConfig);
return nextIncludePath(null);
});
},
err => {
this.configPaths = [ this.baseConfigPath, ...includePaths ];
2020-06-11 01:15:49 +00:00
return cb(err, config);
});
}
_resolveAtSpecs(config) {
2020-06-12 03:38:33 +00:00
return mapValuesDeep(
2020-06-11 01:15:49 +00:00
config,
2020-06-12 03:38:33 +00:00
value => {
2020-06-11 01:15:49 +00:00
if (_.isString(value) && '@' === value.charAt(0)) {
if (value.startsWith('@reference:')) {
2020-06-12 03:38:33 +00:00
const refPath = value.slice(11);
value = _.get(config, refPath, value);
2020-06-11 01:15:49 +00:00
} else if (value.startsWith('@environment:')) {
2020-06-12 03:38:33 +00:00
value = this._resolveEnvironmentVariable(value) || value;
2020-06-11 01:15:49 +00:00
}
}
2020-06-12 03:38:33 +00:00
return value;
2020-06-11 01:15:49 +00:00
}
);
}
};