@gospime/autoloader
Version:
Utility of target modules autoloading
55 lines (45 loc) • 1.34 kB
JavaScript
const Path = require('path');
const rdir = require('require-dir');
module.exports = (path, handler) => {
if (typeof handler !== 'function') {
throw new TypeError('Invalid handler');
}
const basename = Path.basename(path);
if (!basename) throw new Error(`Invalid basename: '${basename}'`);
//console.log(basename);
// take only first level folder or the file `index.js`
const pattern = `${basename}\\/[-\.\\w]+(\\/index\\.js|$)`;
//console.log(pattern);
const regex = new RegExp(pattern, 'i');
const options = {
recurse: true,
filter: function (path) {
//console.log(path, pattern, regex.test(path));
return regex.test(path); // file ignoring
}
};
const set = rdir(path, options);
//console.log(set);
const wrapper = ([key, item]) => {
if (
item &&
typeof item === 'object' &&
Object.prototype.hasOwnProperty.call(item, 'index')
) {
let fn;
const _module = item.index;
if (typeof _module === 'function') {
fn = _module;
} else if (
_module &&
typeof _module === 'object' &&
Object.prototype.hasOwnProperty.call(_module, 'default')
) {
fn = _module.default;
}
//console.log(key, fn);
if (fn) handler(fn);
}
};
Object.entries(set).forEach(wrapper);
};