kwhitley / itty-router

A little router.
MIT License
1.75k stars 78 forks source link

Params vs Defined Paths are combined #71

Closed aligzl closed 2 years ago

aligzl commented 2 years ago

I have tried to build rest api with cloudflare workers. I have fallowing routes

router.post('/rooms/image', withUser, async request => {
  const { post } = request

  const room = await rooms.addImage(post)

  return new Response(JSON.stringify(room, null, 2), heads)
})
router.post('/rooms/:id', withUser, async ({ params, post }) => {

  const room = await rooms.edit(post)

  return new Response(JSON.stringify(room, null, 2), heads)
})

When i sent request to the rooms/:id it takes care of rooms/image. Router does not get correct route releated to regex.

kwhitley commented 2 years ago

I'd need to see entire code here, because that's exactly what itty does handle (and it has heavy test coverage to verify/ensure it).

A couple things:

  1. Where is the post attribute on the request coming from? I assume it comes from somewhere upstream in your code?
  2. Is the heads bit pseudocode replacement of actual headers? That won't work either...
  3. I'd suggest adding itty-router-extras in all cases of itty, as it has other helpers that would make your life easier, for example:
    
    import { Router } from 'itty-router'
    import { json, text, withContent, withParams } from 'itty-router-extras'

const router = Router()

router .post('/somewhere', withContent, ({ content }) => json(content)) // withContent embeds parsed POST body, and json returns JSON response .post('/somewhere/:id', withContent, withParams, ({ content, id }) => // withParams embeds params directly on request text(post saved to id ${id} with content length of ${content.length}) // text() returns text response ) .all('*', request => missing(Cannot find a path for ${request.url})) // missing returns 404 response

kwhitley commented 2 years ago

image This test in the spec covers your exact scenario!

Going to label this as not a bug unless we can find something for sure amiss!

kwhitley commented 2 years ago

Closing this unless more info can be added to reopen! Just let me know!