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
2020-01-08 08:42:55 +01:00

73 lines
1.9 KiB
JavaScript

/* eslint-disable no-console */
/* eslint-disable no-sync */
const fs = require ('fs');
const path = require ('path');
/**
* @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
*/
/**
* Load all request handlers in the given folder
*
* @param {any} app express app
* @param {string} modulefolder folder that contains all modules
* @param {options} options additional options
*/
module.exports = function main (
app,
modulefolder,
options = { opts: null, subdir: '', verbose: false }
) {
const { opts, subdir, verbose } = options;
for (const f of fs.readdirSync (modulefolder)) {
const regex = /(?<method>.*?)-(?<url>.*?)\.js/u;
const { groups } = regex.exec (f);
if ('undefined' !== typeof subdir)
groups.url = `/${subdir}/${groups.url}/`;
groups.url = groups.url
.replace (/^\/[^/]*\/root/iu, '/')
.replace (/\./gu, '/')
.replace (/\/+/gu, '/');
// 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);
};
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`
);
break;
}
}
};