我正在写一个库,为所有的路由添加验证,以便与 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
似乎只在 "下游 "被填充,所以是在将要执行的路由处理程序的级别。我想访问这些参数,而不需要在每个路由处理程序之前定义中间件。有什么方法可以实现这个目标吗?
你基本上有两个选择。
我认为这两种方案都是有效的。如果性能非常重要,你可能会从选项2中得到更多,因为你不需要两次解析路由。