获取全路径中间件Koa-router的映射路径参数。

问题描述 投票:0回答:1

我正在写一个库,为所有的路由添加验证,以便与 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 似乎只在 "下游 "被填充,所以是在将要执行的路由处理程序的级别。我想访问这些参数,而不需要在每个路由处理程序之前定义中间件。有什么方法可以实现这个目标吗?

koa koa-router
1个回答
0
投票

你基本上有两个选择。

  1. 使用与koa-route相同的库来解析路由,并从URL中提取这些参数。
  2. 用你自己的中间件来封装koa-route,这样你就有可能成为第一个被调用的中间件。之后 koa-route,然后调用常规的后路由中间件。

我认为这两种方案都是有效的。如果性能非常重要,你可能会从选项2中得到更多,因为你不需要两次解析路由。

© www.soinside.com 2019 - 2024. All rights reserved.