/* eslint-disable no-console */ /* eslint-disable no-sync */ 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 * @property {boolean} [rethrow] rethrow errors (default: true) */ /** * Load all request handlers in the given folder * * @param {any} app express app * @param {string} modulefolder folder that contains all modules * @param {options} options additional options */ module.exports = function main ( app, modulefolder, options = { opts: null, subdir: '', verbose: false, rethrow: true } ) { const { opts, subdir, verbose, rethrow } = options; for (const f of fs.readdirSync (modulefolder)) { const regex = /(?.*?)-(?.*?)\.js/u; const { groups } = regex.exec (f); if (typeof subdir === 'undefined') groups.url = `/${groups.url}/`; else groups.url = `/${subdir}/${groups.url}/`; groups.url = groups.url .replace (/^\/[^/]*\/root/iu, '/') .replace (/\./gu, '/') .replace (/\/+/gu, '/'); // eslint-disable-next-line global-require const handler = require (path.join (process.cwd (), modulefolder, f)); const requestor_handler = (req, res, next) => { try { handler (req, res, next, opts); } catch (e) { if (rethrow) throw e; else console.error (e); } }; if (verbose) console.log (`[requestor info] redirecting ${groups.url} to ${f}`); switch (groups.method) { case 'post': app.post (groups.url, requestor_handler); break; case 'get': app.get (groups.url, requestor_handler); break; case 'put': app.put (groups.url, requestor_handler); break; case 'delete': app.delete (groups.url, requestor_handler); break; case 'all': app.all (groups.url, requestor_handler); break; default: if (verbose) console.warn ( `'${groups.method}' did not match any request method, ignoring` ); break; } } };