const fs = require('fs'); const path = require('path'); /** * Load all request handlers in the given folder * * @param {any} app express app * @param {string} modulefolder * @param {any} opts object to pass to the handlers (for example database access) * @param {string} subdir subdirectory for all requests (app will respond to /subdir/... instead of /...) */ module.exports = function (app, modulefolder, opts = {}, subdir = '') { 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); }; 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; } } };