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

Nested routers middleware order? #156

Closed
jpetitcolas opened this issue Jul 29, 2015 · 1 comment
Closed

Nested routers middleware order? #156

jpetitcolas opened this issue Jul 29, 2015 · 1 comment

Comments

@jpetitcolas
Copy link

I got the following code:

var app = koa();

var router = require('koa-router')();
router.use(function* (next) {
    console.log('Router middleware');
    yield next;
});

var subRouter = require('koa-router')();
subRouter.use(function* (next) {
    console.log('Subrouter middleware');
    yield next;
});

subRouter.get('/', function*() {
    this.body = 'Hello world!';
});

router.use('', subRouter.middleware());

app
    .use(router.routes())
    .use(router.allowedMethods());

When I go on / route, I got the following debug messages:

Subrouter middleware
Router middleware

I would expect the opposite order, as I registered the router middleware first. Is it the expected behavior? If so, have you any clue to reverse this order?

My use case is quite standard: I got a main router in which I initialize a database connection through a middleware (setting it in a this.dbClient property). Then, my subrouters (one per API) initialize its model repository via another middleware, passing it the dbClient service. The repository is then in an attribute to factorize code between all CRUD methods.

@neVERberleRfellerER
Copy link

Problem is here
https:/alexmingoia/koa-router/blob/master/lib/router.js#L256
normal use is using unshift, but when used with nested router, it uses push. Replacing push with unshift fixes this. I am not sure about side effects.

Update: following happens only when both subrouters are mounted to same path
However, there is bigger problem than this. when you use multiple subrouters, each with different middleware, this sentence from docs: Only runs if any route is matched is no longer true. When one subrouter matches, middlewares from all subrouter are run.

alexmingoia added a commit that referenced this issue Sep 27, 2015
- Fixes #161, fixes #155, fixes #156.
- Removes dependency on koa-compose.
ruiquelhas pushed a commit to seegno-forks/koa-router that referenced this issue Oct 16, 2015
ruiquelhas pushed a commit to seegno-forks/koa-router that referenced this issue Oct 16, 2015
- Fixes ZijianHe#161, fixes ZijianHe#155, fixes ZijianHe#156.
- Removes dependency on koa-compose.
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