2020-01-03 19:13:21 +01:00
|
|
|
/* eslint-disable no-console */
|
|
|
|
/* eslint-disable no-sync */
|
|
|
|
const fs = require ('fs');
|
|
|
|
const path = require ('path');
|
2019-12-10 15:59:12 +01:00
|
|
|
|
2019-12-11 13:07:48 +01:00
|
|
|
/**
|
2020-01-03 19:13:21 +01:00
|
|
|
* @typedef {object} options
|
2019-12-11 13:07:48 +01:00
|
|
|
* @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
|
2020-01-03 19:13:21 +01:00
|
|
|
* @param {options} options additional options
|
2019-12-10 15:59:12 +01:00
|
|
|
*/
|
2020-01-03 19:13:21 +01:00
|
|
|
module.exports = function main (
|
2019-12-11 12:57:05 +01:00
|
|
|
app,
|
|
|
|
modulefolder,
|
2020-01-03 19:13:21 +01:00
|
|
|
options = { opts: null, subdir: '', verbose: false }
|
2019-12-11 12:57:05 +01:00
|
|
|
) {
|
|
|
|
const { opts, subdir, verbose } = options;
|
2019-12-11 12:55:30 +01:00
|
|
|
|
2020-01-03 19:13:21 +01:00
|
|
|
for (const f of fs.readdirSync (modulefolder)) {
|
|
|
|
const regex = /(?<method>.*?)-(?<url>.*?)\.js/u;
|
|
|
|
const { groups } = regex.exec (f);
|
|
|
|
groups.url = `/${subdir}/${groups.url}/`;
|
|
|
|
groups.url = groups.url
|
|
|
|
.replace (/^\/[^/]*\/root/iu, '/')
|
|
|
|
.replace (/\./gu, '/')
|
|
|
|
.replace (/\/+/gu, '/');
|
2019-12-10 15:59:12 +01:00
|
|
|
|
2020-01-03 19:13:21 +01:00
|
|
|
// eslint-disable-next-line global-require
|
|
|
|
const handler = require (path.join (process.cwd (), modulefolder, f));
|
|
|
|
|
|
|
|
const requestor_handler = (req, res, next) => {
|
|
|
|
handler (req, res, next, opts);
|
2019-12-10 15:59:12 +01:00
|
|
|
};
|
|
|
|
|
2020-01-03 19:13:21 +01:00
|
|
|
if (verbose)
|
|
|
|
console.log (`[requestor info] redirecting ${groups.url} to ${f}`);
|
|
|
|
|
|
|
|
switch (groups.method) {
|
|
|
|
case 'post':
|
|
|
|
app.post (groups.url, requestor_handler);
|
|
|
|
break;
|
|
|
|
case 'get':
|
|
|
|
app.get (groups.url, requestor_handler);
|
|
|
|
break;
|
|
|
|
case 'put':
|
|
|
|
app.put (groups.url, requestor_handler);
|
|
|
|
break;
|
|
|
|
case 'delete':
|
|
|
|
app.delete (groups.url, requestor_handler);
|
|
|
|
break;
|
|
|
|
case 'all':
|
|
|
|
app.all (groups.url, requestor_handler);
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
if (verbose)
|
|
|
|
console.warn (
|
|
|
|
`'${groups.method}' did not match any request method, ignoring`
|
|
|
|
);
|
2019-12-11 12:55:30 +01:00
|
|
|
|
2020-01-03 19:13:21 +01:00
|
|
|
break;
|
2019-12-10 15:59:12 +01:00
|
|
|
}
|
|
|
|
}
|
2019-12-11 09:32:40 +01:00
|
|
|
};
|