const fs = require('fs'); const path = require('path'); /** * @typedef {Object} options * @property {any} [opts] object to pass to the handlers * @property {string} [subdir] subdirectory for all requests * @property {boolean} [verbose] enable verbose logging */ /** * Load all request handlers in the given folder * * @param {any} app express app * @param {string} modulefolder folder that contains all modules * @param {options} options */ module.exports = function ( app, modulefolder, options = { opts: undefined, subdir: '', verbose: false } ) { const { opts, subdir, verbose } = options; for (const f of fs.readdirSync(modulefolder)) { const regex = /(.*?)-(.*?)\.js/; let [, method, url] = regex.exec(f); url = '/' + subdir + '/' + url + '/'; url = url .replace(/^\/[^/]*\/root/i, '/') .replace(/\./g, '/') .replace(/\/+/g, '/'); const handler = require(path.join(process.cwd(), modulefolder, f)); const func = (req, res, next) => { handler(req, res, next, opts); }; if (verbose) console.log(`[requestor info] redirecting ${url} to ${f}`); switch (method) { case 'post': app.post(url, func); break; case 'get': app.get(url, func); break; case 'put': app.put(url, func); break; case 'delete': app.delete(url, func); break; case 'all': app.all(url, func); break; default: if (verbose) { console.warn(`'${method}' did not match any request method, ignoring`); } break; } } };