ZijianHe / koa-router

Router middleware for koa.
MIT License
4.85k stars 407 forks source link

populate `ctx.params` before running any matched middleware #490

Open smkoyan opened 5 years ago

smkoyan commented 5 years ago

The problem is that when I use router.use(someMiddleware), in that middleware I have access to payload from query string via ctx.query and to payload from request body via ctx.request.body but I haven't access to route params and this is not so convenient especially in my case.

To be more clear I will tell my story. I have a validation middleware which works like this. It takes request method from ctx.request.method and matched route from ctx._matchedRoute and using that it takes necessary validation rules from validation schemas that look like this:

'PUT:/users/:id': {
    params: Joi.object().keys({
        id: Joi.string().length(24).alphanum().required(),
    }),

    query: Joi.object().keys(definitions),

    body: Joi.object().keys(definitions)
}

and for each type of payload, if it exists in the scheme, it checks for validity and problem comes here when it tries to validate params because params are not available in the middleware defined using router.use method.

This pull request fixes this type of problems and I think this will will bring much good in the future.

Thanks!

tranan89 commented 5 years ago

We need this as well

divmgl commented 5 years ago

This is huge. @ZijianHe can you please merge this?

divmgl commented 5 years ago

@smkoyan thanks for your work on this. this resolves ~most~ one of my issues with Router.prototype.param.