koajs / router

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

Unable to reuse nested routers (router mutation) #18

Closed MarcusCemes closed 4 years ago

MarcusCemes commented 5 years ago

I wanted to reopen an issue that never got fixed in the old unmaintained koa-router. https://github.com/ZijianHe/koa-router/issues/244#issuecomment-184696207

Tested with

koa-router version: 8.0.0

koa version: 2.7.0

Code sample:

sharedRouter.get('/hello', (ctx) => {
    ctx.body = 'Hello World!';
});

rootRouter.use(sharedRouter.routes());
rootRouter.use('/foo', sharedRouter.routes());
rootRouter.use('/bar', sharedRouter.routes());

app.use(rootRouter.routes());

Expected Behavior:

The following paths should return a Hello World! body:

Actual Behavior:

Each route returns a 404, as koa is unable to match a route.

Each time the shared router is mounted (.routes() is called), the shared router is mutated, with the new mounted path being prefixed to the shared router. The resulting route for the shared router is /bar/foo/hello, which I believe is then tested three times.

Use case

While this can easily be avoided, it is an inconvenience and unpredictable behaviour.

A mutation is not predictable. My understanding is that routers should behave like self-contained packages that can be mounted dynamically in several places, providing the same route tree.

niftylettuce commented 4 years ago

https://github.com/koajs/router/pull/24#issuecomment-563359492