DEV Community

Ramu Narasinga
Ramu Narasinga

Posted on • Originally published at thinkthroo.com

rou3 library in Nitro codebase.

In this article, we review rou3 library in Nitro codebase. We will look at:

  1. What is rou3 library?

  2. rou3 library in Nitro.

I study patterns used in an open source project found on Github Trending. For this week, I reviewed some parts of Nitro codebase and wrote this article.

Press enter or click to view image in full size

What is rou3 library?

Lightweight and fast rou(ter) for JavaScript.

Install

#  Auto-detect
npx nypm install rou3
Enter fullscreen mode Exit fullscreen mode

Create a router instance and insert routes:

import { createRouter, addRoute } from "rou3";

const router = createRouter(/* options */);

addRoute(router, "GET", "/path", { payload: "this path" });
addRoute(router, "POST", "/path/:name", { payload: "named route" });
addRoute(router, "GET", "/path/foo/**", { payload: "wildcard route" });
addRoute(router, "GET", "/path/foo/**:name", {
  payload: "named wildcard route",
});
Enter fullscreen mode Exit fullscreen mode

Match route to access matched data:

// Returns { payload: 'this path' }
findRoute(router, "GET", "/path");

// Returns { payload: 'named route', params: { name: 'fooval' } }
findRoute(router, "POST", "/path/fooval");

// Returns { payload: 'wildcard route' }
findRoute(router, "GET", "/path/foo/bar/baz");

// Returns undefined (no route matched for/)
findRoute(router, "GET", "/");
Enter fullscreen mode Exit fullscreen mode

rou3 library in Nitro.

At L13 in prerender.ts file, you will find the below import:

import { createRouter, addRoute, findAllRoutes } from "rou3";
Enter fullscreen mode Exit fullscreen mode

and below is how prerender creates routes, found at L113:

// Create route rule matcher
const routeRules = createRouter<NitroRouteRules>();
for (const [route, rules] of Object.entries(nitro.options.routeRules)) {
  addRoute(routeRules, undefined, route, rules);
}
Enter fullscreen mode Exit fullscreen mode

findAllRoutes is called in _getRouteRules function.

const _getRouteRules = (path: string) =>
  defu(
    {},
    ...findAllRoutes(routeRules, undefined, path)
      .map((r) => r.data)
      .reverse()
  ) as NitroRouteRules;
Enter fullscreen mode Exit fullscreen mode

About me:

Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.

Email: ramu.narasinga@gmail.com

Study the patterns used in large OSS projects at Think Throo.

References:

  1. https://github.com/h3js/rou3

  2. https://github.com/nitrojs/nitro/blob/main/src/prerender/prerender.ts#L13

  3. https://github.com/nitrojs/nitro/blob/main/src/prerender/prerender.ts#L121

Top comments (0)