Compare commits
4 Commits
b2d9e9f0bf
...
a73e0d1d80
Author | SHA1 | Date | |
---|---|---|---|
|
a73e0d1d80 | ||
|
6baeade4c0 | ||
|
1534917132 | ||
|
0c4ccc3b43 |
27
index.js
27
index.js
@ -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;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -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/',
|
||||
|
Reference in New Issue
Block a user