kwhitley / itty-router

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

Nestable routers not inheriting base #23

Closed SRugina closed 3 years ago

SRugina commented 3 years ago

Perhaps this is a point that needs to be clarified in the documentation, but contrary to what "Nestable" and "API Branching" imply, nestable routers do not inherit the parent's base. To illustrate, an adapted version of the example in the README:

// lets save a missing handler
const missingHandler = new Response('Not found.', { status: 404 })

// create a parent router at /api
const parentRouter = Router({ base: '/api' })

// and a child router
const todosRouter = Router({ base: '/todos' })

// with some routes on it...
todosRouter
  .get('/', () => new Response('Todos Index'))
  .get('/:id', ({ params }) => new Response(`Todo #${params.id}`))

// then divert ALL requests to /api/todos/* into the child router
parentRouter
  .all('/todos/*', todosRouter.handle) // attach child router
  .all('*', missingHandler) // catch any missed routes

// GET /api/todos --> missingHandler
// GET /api/todos/13 --> missingHandler
// POST /api/todos --> missingHandler (caught eventually by parentRouter)
// GET /api/foo --> missingHandler

To make the above work, one would have to change the base of todosRouter to be /api/todos.

kwhitley commented 3 years ago

Certainly a challenge with this one, no doubt... I'll add clarification to the docs around nesting to specify the need for an explicit full path at the child router level. This occurs because each router is currently (and perhaps forever) unaware of any parent router that may have called it. Each handler/router executes in complete isolation.

That said, you can achieve nestability/branching within these constraints, as that simply means a single route (within a parent router) can handle many routes (within a child router), thus "branching" and "nestability" both. That you have to define the end path within the child is inconvenient, but ultimately does nothing to prevent the functionality...

It's the price we pay for a ~450 byte router! :)

I'll leave this open till I add clarification to the docs (or in the near-impossible chance I can squeeze in this certainly preferable handling of parent base paths from a child without adding a ton of characters). Of course, you're also welcome to take a stab at doing that with a PR... knowing that itty should you know, remain "itty", haha.

kwhitley commented 3 years ago

@SRugina as of v2.2+ the Nestable example is updated to direct attention to this pattern, with disclaimers below the example.

Wish I had a silver bullet for this one, but like I said... brevity comes at a price :p There are definitely other more feature-rich (but much larger) routers out there that I'm sure cover this issue with ease!