koajs / router

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

Route followed by required verbs and handler syntax #141

Closed antonpious closed 2 months ago

antonpious commented 2 years ago

@koa/router version: 10.1.1 koa version: 2.13.4

Code sample:

In express route if we want to match multiple verbs with the same route we could provide the following syntax

express.route("/api/:type:id?")
    .post(handler)
    .get(handler)
    .delete(handler);

What is the equivalent syntax in Koa Router? Currently its expecting the route to be repeated.

router
  .get('/users, handler)
  .post('/users', handler)
  .del('/users/:id', handler);

Does the router support optional parameters?

zacanger commented 1 year ago

I know this question is a little old, but I wanted to answer in case someone else comes across this in a search.

Your example of method (and HTTP method) chaining is correct. If that's too verbose, you could use a router.all and reject methods that you don't like. Example:

router.all('/foo', (ctx, next) => {
  const allowed = ['GET', 'POST']
  const isCorrect = allowed.includes(ctx.method)
  ctx.assert(ctx, 405, "Ah nah man that's not right")
})

As for optional path segments: yes, and if you need more complicated options you can use more Regex. Anything supported by path-to-regexp should be supported here, with obvious caveats like needing extra escapes for some characters.