Closed vanodevium closed 3 weeks ago
I think the case where we have to do the same job using multiple methods is rare.
Thanks @vanodevium for your contribution, as @etroynov mentioned this use case is very rare and you can create HOF as a helper, something like;
function withMultiVerbs(Router) {
/**
* Register route with concrete verbs.
*
* @param {Array} verbs
* @param {String} name Optional.
* @param {String} path
* @param {Function=} middleware You may also pass multiple middleware.
* @param {Function} callback
* @returns {Router}
*/
Router.prototype.verbs = function (verbs, path, middleware) {
if (!Array.isArray(verbs) || verbs.length === 0) {
throw new Error(
'You have to provide a list of verbs when adding an verbs handler'
);
}
if (typeof path === 'string') {
middleware = Array.prototype.slice.call(arguments, 2);
}
// Sanity check to ensure we have a viable path candidate (eg: string|regex|non-empty array)
if (
typeof path !== 'string' &&
!(path instanceof RegExp) &&
(!Array.isArray(path) || path.length === 0)
)
throw new Error('You have to provide a path when adding an all handler');
this.register(
path,
verbs.map((verb) => verb.toLowerCase()),
middleware
);
return this;
};
return Router;
}
where the usage will be like;
const Router = withMultiVerbs('@koa/router');
BTW, you can contribute later to add your module to the recipes section.
Checklist
Route#verbs()
First of all, I created this method just as an idea.
In fact, this method will be useful in cases where the callback is just an anonymous function and you need to assign it to several HTTP methods.
I absolutely understand that it could be done this way:
but for dynamic programming this method would be much more useful.