All files / middlewares autoloader.js

90% Statements 18/20
91.67% Branches 11/12
100% Functions 2/2
90% Lines 18/20
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          1x 1x   1x 8x 5x   3x 3x 3x 3x 1x   2x 2x 5x     5x 5x         5x 5x 5x            
/**
 * Autoloader middleware
 **/
'use strict';
 
const assert          = require('assert');
const LarkAutoLoader  = require('lark-autoloader');
 
module.exports = async (app) => {
    if (!app.config.has('autoloader')) {
        return;
    }
    const key = app.config.has('autoloader/name') ? app.config.get('autoloader/name') : '$';
    assert(app.config.has('autoloader/directory'), 'No auto loading directory');
    const directories = app.config.get('autoloader/directory');
    if (!(directories instanceof Object) || Object.keys(directories).length <= 0) {
        return;
    }
    global[key] = global[key] || {};
    for (const name in directories) {
        Iif (global[key].hasOwnProperty(name)) {
            continue;
        }
        global[key][name] = {};
        await autoload(global[key][name], directories[name]);
    }
};
 
async function autoload(target, directory) {
    const autoloader = new LarkAutoLoader(target);
    try {
        await autoloader.load(directory);
    }
    catch (error) {
        throw new Error(`Can not load ${directory}: ${error.message}`);
    }
}