koajs / router

Router middleware for Koa. Maintained by @forwardemail and @ladjs.
MIT License
849 stars 174 forks source link

Router#verbs() #169

Closed vanodevium closed 3 weeks ago

vanodevium commented 1 year ago

Checklist

xo linting is broken and I have no idea how to fix it


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.


router.verbs(['get', 'post'], '/endpoint', function (ctx) {
    ctx.body = "Ok"
})

I absolutely understand that it could be done this way:


router.get('/endpoint', middleware());
router.post('/endpoint', middleware());

but for dynamic programming this method would be much more useful.

etroynov commented 12 months ago

I think the case where we have to do the same job using multiple methods is rare.

3imed-jaberi commented 3 weeks ago

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.