Compare commits

..

4 Commits

Author SHA1 Message Date
Timo Hocker
a73e0d1d80 logging in case method was not found 2019-12-11 13:10:45 +01:00
Timo Hocker
6baeade4c0 fix documentation 2019-12-11 13:07:48 +01:00
Timo Hocker
1534917132 fix options default 2019-12-11 12:57:05 +01:00
Timo Hocker
0c4ccc3b43 add verbose logging, optional args structured as options 2019-12-11 12:55:30 +01:00
2 changed files with 24 additions and 5 deletions

View File

@ -1,15 +1,27 @@
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
* @param {any} opts object to pass to the handlers (for example database access)
* @param {string} subdir subdirectory for all requests (app will respond to /subdir/... instead of /...)
* @param {string} modulefolder folder that contains all modules
* @param {options} options
*/
module.exports = function (app, modulefolder, opts = {}, subdir = '') {
module.exports = function (
app,
modulefolder,
options = { opts: undefined, subdir: '', verbose: false }
) {
const { opts, subdir, verbose } = options;
for (const f of fs.readdirSync(modulefolder)) {
const regex = /(.*?)-(.*?)\.js/;
let [, method, url] = regex.exec(f);
@ -24,6 +36,8 @@ module.exports = function (app, modulefolder, opts = {}, subdir = '') {
handler(req, res, next, opts);
};
if (verbose) console.log(`[requestor info] redirecting ${url} to ${f}`);
switch (method) {
case 'post':
app.post(url, func);
@ -40,6 +54,11 @@ module.exports = function (app, modulefolder, opts = {}, subdir = '') {
case 'all':
app.all(url, func);
break;
default:
if (verbose) {
console.warn(`'${method}' did not match any request method, ignoring`);
}
break;
}
}
};

View File

@ -63,7 +63,7 @@ describe('requestor', () => {
});
it('should build requests with subdirectory', () => {
requestor(mock, './test/sub', {}, 'test');
requestor(mock, './test/sub', { subdir: 'test' });
expect(mock.registered).to.have.all.keys([
'post-/test/sub/',
'get-/test/sub/',