app2-api/core/modules.js
2019-04-15 12:13:17 +02:00

58 lines
1.3 KiB
JavaScript

'use strict';
// Dependencies.
const glob = require('glob');
const { setWith, merge, get, isObject, isFunction } = require('lodash');
const optionalPath = path => {
return path
.replace(/(\.settings|.json|.js)/g, '')
.split('/')
.slice(1, path.split('/').length - 1)
.join('.')
.toLowerCase();
};
const aggregatePath = path => {
return path
.replace(/(\.settings|.json|.js)/g, '')
.split('/')
.slice(1)
.join('.')
.toLowerCase();
};
const setConfig = function (ctx, path, type, loader) {
const objPath = type === 'optional' ?
optionalPath(path) :
aggregatePath(path);
// Load value.
const value = loader(path);
// Merge doesn't work for none-object value and function.
const obj = isObject(value) && !isFunction(value) ? merge(get(ctx, objPath), value) : value;
// Assignation.
return setWith(ctx, objPath, obj, Object);
};
module.exports = function() {
return Promise.all([
new Promise((resolve, reject) => {
// Load configurations.
glob('./modules/*/!(config)/*.*(js|json)', {
cwd: this.config.appPath
}, (err, files) => {
if (err) {
return reject(err);
}
files.map(p => setConfig(this, p, 'aggregate', this.loadFile));
resolve();
});
}),
]);
};