我正在编写一个库,它为所有路由添加验证,以便与koa-router一起使用。
在我的routes/index.js文件中,在运行任何路由之前,我能够通过使用以下代码获得我想要的大部分内容:
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;
}不幸的是,ctx.params似乎只填充了“下游”,所以在要执行的路由处理程序级别。我希望能够访问这些参数,而不必在每个路由处理程序之前定义我的中间件。有没有办法做到这一点?
发布于 2020-04-20 03:21:53
你基本上有两个选择:
我认为这两个都是有效的选择。如果性能非常重要,您可能会对选项2有更多的了解,因为您不需要对路由进行两次解析。
https://stackoverflow.com/questions/61310216
复制相似问题