2019-12-10 15:59:12 +01:00
|
|
|
const fs = require('fs');
|
2019-12-11 11:27:35 +01:00
|
|
|
const path = require('path');
|
2019-12-10 15:59:12 +01:00
|
|
|
|
2019-12-11 13:07:48 +01:00
|
|
|
/**
|
|
|
|
* @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
|
|
|
|
*/
|
|
|
|
|
2019-12-10 15:59:12 +01:00
|
|
|
/**
|
|
|
|
* Load all request handlers in the given folder
|
|
|
|
*
|
2019-12-11 09:32:40 +01:00
|
|
|
* @param {any} app express app
|
2019-12-11 12:55:30 +01:00
|
|
|
* @param {string} modulefolder folder that contains all modules
|
2019-12-11 13:07:48 +01:00
|
|
|
* @param {options} options
|
2019-12-10 15:59:12 +01:00
|
|
|
*/
|
2019-12-11 12:57:05 +01:00
|
|
|
module.exports = function (
|
|
|
|
app,
|
|
|
|
modulefolder,
|
|
|
|
options = { opts: undefined, subdir: '', verbose: false }
|
|
|
|
) {
|
|
|
|
const { opts, subdir, verbose } = options;
|
2019-12-11 12:55:30 +01:00
|
|
|
|
2019-12-10 15:59:12 +01:00
|
|
|
for (const f of fs.readdirSync(modulefolder)) {
|
|
|
|
const regex = /(.*?)-(.*?)\.js/;
|
|
|
|
let [, method, url] = regex.exec(f);
|
2019-12-11 12:17:29 +01:00
|
|
|
url = '/' + subdir + '/' + url + '/';
|
2019-12-11 09:56:39 +01:00
|
|
|
url = url
|
2019-12-11 12:27:39 +01:00
|
|
|
.replace(/^\/[^/]*\/root/i, '/')
|
2019-12-11 09:56:39 +01:00
|
|
|
.replace(/\./g, '/')
|
|
|
|
.replace(/\/+/g, '/');
|
2019-12-10 15:59:12 +01:00
|
|
|
|
2019-12-11 11:27:35 +01:00
|
|
|
const handler = require(path.join(process.cwd(), modulefolder, f));
|
2019-12-10 15:59:12 +01:00
|
|
|
const func = (req, res, next) => {
|
|
|
|
handler(req, res, next, opts);
|
|
|
|
};
|
|
|
|
|
2019-12-11 12:55:30 +01:00
|
|
|
if (verbose) console.log(`[requestor info] redirecting ${url} to ${f}`);
|
|
|
|
|
2019-12-10 15:59:12 +01:00
|
|
|
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 13:10:45 +01:00
|
|
|
default:
|
|
|
|
if (verbose) {
|
|
|
|
console.warn(`'${method}' did not match any request method, ignoring`);
|
|
|
|
}
|
|
|
|
break;
|
2019-12-10 15:59:12 +01:00
|
|
|
}
|
|
|
|
}
|
2019-12-11 09:32:40 +01:00
|
|
|
};
|