I'm writing a library that adds validation to all routes, for use with koa-router
.
In my routes/index.js
file, before running any routes, I'm able to get most of what I want to achieve by using the following code:
let routePath = ctx._matchedRoute as string;
if (!routePath) {
return next();
}
// Strip trailing slash and replace colon with underscore
let routeName = routePath.replace(/\/$/, "").replace(/:/g, "_");
let schemaName = `/requests/${ctx.method}${routeName}.json`;
if (!hasSchema(schemaName)) {
return next();
}
try {
await validate(schemaName, {
query: ctx.query,
params: ctx.params,
body: ctx.request.body,
headers: ctx.headers
});
return next();
} catch (err) {
throw err;
}
Unfortunately, ctx.params
seems to be only populated "downstream", so at the level of the to-be-executed route handler. I'd like to get access to these parameters without having to define my middleware before each and every route handler. Is there a way to achieve this?