将路由器路由到 Oak 框架中的另一个路由器,例如 ExpressJS

Route router to another router in Oak framework like ExpressJS

我想要实现的是创建多个路由器和一个将请求路由到其他路由器的主路由器。

router.use("/strategy", strategyRoutes);
router.use("/account", accountRoutes);

router、strategyRoutes 和 accountRoutes 是 express.Router() 对象。我可以快速做到这一点 我想知道在 Deno 的 Oak 框架中是否有任何方法可以模仿它。他们的路由器有一个 router.use 功能,但它接受一个中间件功能而不是另一个路由器。

目前不支持,关于此功能有一个未解决的问题:

https://github.com/oakserver/oak/issues/6

查看问题后,我找到了解决此问题的方法。我想要此功能的原因是将路由逻辑封装在不同的模块中。我的解决方案是:

// router/index.ts

import { Router } from "https://deno.land/x/oak/mod.ts";
import withAccountRoutes from "./account.ts";
import withContractRoutes from "./contract.ts";
const router = new Router();
withAccountRoutes(router);
withContractRoutes(router);
export default router;

// router/account.ts

import { Router } from "https://deno.land/x/oak/mod.ts";

const SUB_ROUTE = "/account";

const withAccountRoutes = (router: Router) => {
  router
    .get(SUB_ROUTE + "/new", ({ request, response, cookies }) => {
      console.log("Cookies : ", cookies);
      response.body = "Will be avaiable soon";
    })
    .get(SUB_ROUTE + "/current", ({ request, response, cookies }) => {
      response.body = "You are the wise one";
    });
};

export default withAccountRoutes;