Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Route followed by required verbs and handler syntax #141

Open
antonpious opened this issue Jan 14, 2022 · 1 comment
Open

Route followed by required verbs and handler syntax #141

antonpious opened this issue Jan 14, 2022 · 1 comment

Comments

@antonpious
Copy link

antonpious commented Jan 14, 2022

@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?

@antonpious antonpious changed the title Route separate followed by all the verbs and handler syntax Route followed by required verbs and handler syntax Jan 14, 2022
@zacanger
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants