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

40 lines
1.0 KiB
JavaScript
Raw Normal View History

2019-12-10 15:59:12 +01:00
const fs = require('fs');
/**
* Load all request handlers in the given folder
*
2019-12-11 09:32:40 +01:00
* @param {any} app express app
2019-12-10 15:59:12 +01:00
* @param {string} modulefolder
2019-12-11 09:32:40 +01:00
* @param {any} opts object to pass to the handlers (for example database access)
2019-12-10 15:59:12 +01:00
*/
module.exports = function (app, modulefolder, opts) {
for (const f of fs.readdirSync(modulefolder)) {
const regex = /(.*?)-(.*?)\.js/;
let [, method, url] = regex.exec(f);
2019-12-11 09:32:40 +01:00
url = '/' + url.replace(/^root/i, '').replace(/\./g, '/').replace(/\/+/g, '/');
2019-12-10 15:59:12 +01:00
2019-12-11 09:32:40 +01:00
const handler = require(('./' + modulefolder + '/' + f).replace(/\/\.\//g, '/').replace(/\/+/g, '/'));
2019-12-10 15:59:12 +01:00
const func = (req, res, next) => {
handler(req, res, next, opts);
};
switch (method) {
case 'post':
2019-12-11 09:32:40 +01:00
app.post(url, func);
2019-12-10 15:59:12 +01:00
break;
case 'get':
2019-12-11 09:32:40 +01:00
app.get(url, func);
2019-12-10 15:59:12 +01:00
break;
case 'put':
2019-12-11 09:32:40 +01:00
app.put(url, func);
2019-12-10 15:59:12 +01:00
break;
case 'delete':
2019-12-11 09:32:40 +01:00
app.delete(url, func);
2019-12-10 15:59:12 +01:00
break;
case 'all':
2019-12-11 09:32:40 +01:00
app.all(url, func);
2019-12-10 15:59:12 +01:00
break;
}
}
2019-12-11 09:32:40 +01:00
};