41 lines
1020 B
JavaScript
41 lines
1020 B
JavaScript
|
const fs = require('fs');
|
||
|
const path = require('path');
|
||
|
|
||
|
/**
|
||
|
* Load all request handlers in the given folder
|
||
|
*
|
||
|
* @param {any} express app
|
||
|
* @param {string} modulefolder
|
||
|
* @param {any} 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.replace(/^root/i, '').replace(/\./g, '/').replace(/\/\//g, '');
|
||
|
|
||
|
const handler = require(path.join('./', modulefolder, f));
|
||
|
const func = (req, res, next) => {
|
||
|
handler(req, res, next, opts);
|
||
|
};
|
||
|
|
||
|
switch (method) {
|
||
|
case 'post':
|
||
|
app.post(path, func);
|
||
|
break;
|
||
|
case 'get':
|
||
|
app.get(path, func);
|
||
|
break;
|
||
|
case 'put':
|
||
|
app.put(path, func);
|
||
|
break;
|
||
|
case 'delete':
|
||
|
app.delete(path, func);
|
||
|
break;
|
||
|
case 'all':
|
||
|
app.all(path, func);
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
}
|