Route router to another router in Oak framework like ExpressJS

806 Views Asked by At

Thing I want to achieve is create multiple routers and a main router that routes requests to other routers.

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

router,strategyRoutes and accountRoutes are express.Router() objects. I can do it in express I wonder is there any way to mimic this in Deno's Oak Framework. Their router has a router.use function but it accepts a middleware function not another router.

2

There are 2 best solutions below

0
On BEST ANSWER

Currently, it's not supported, there's an open issue regarding this feature:

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

0
On

After reviewing the issue I found a work around for this issue. The reason I wanted this feature was to encapsulate the routing logic in different modules. My solution is :

// 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;