This repository has been archived on 2020-08-13. You can view files and clone it, but cannot push or open issues or pull requests.
requestor/index.js
2019-12-11 09:56:39 +01:00

46 lines
1.1 KiB
JavaScript

const fs = require('fs');
/**
* 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)
*/
module.exports = function (app, modulefolder, opts) {
for (const f of fs.readdirSync(modulefolder)) {
const regex = /(.*?)-(.*?)\.js/;
let [, method, url] = regex.exec(f);
url = '/' + url + '/';
url = url
.replace(/^\/root/i, '/')
.replace(/\./g, '/')
.replace(/\/+/g, '/');
const handler = require(('./' + modulefolder + '/' + f)
.replace(/\/\.\//g, '/')
.replace(/\/+/g, '/'));
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;
}
}
};