The Principal Dev – Masterclass for Tech Leads

The Principal Dev – Masterclass for Tech LeadsNov 27-28

Join

🌳 rou3

npm version npm downloads bundle size codecov

Lightweight and fast router for JavaScript.

Usage

Install:

# ✨ Auto-detect
npx nypm install rou3

Import:

ESM (Node.js, Bun, Deno)

import {
  createRouter,
  addRoute,
  findRoute,
  removeRoute,
  findAllRoutes,
  routeToRegExp,
  NullProtoObj,
} from "rou3";

CDN (Deno and Browsers)

import {
  createRouter,
  addRoute,
  findRoute,
  removeRoute,
  findAllRoutes,
  routeToRegExp,
  NullProtoObj,
} from "https://esm.sh/rou3";

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",
});

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", "/");

Experimental Compiler

[!IMPORTANT] Compiler is an experimental feature, may contain issues and the API may change between versions. See #156 for more context.

compileRouter(router, opts?)

Compiles the router instance into a faster route-matching function.

IMPORTANT: compileRouter requires eval support with new Function() in the runtime for JIT compilation.

Example:

import { createRouter, addRoute } from "rou3";
import { compileRouter } from "rou3/compiler";
const router = createRouter();
// [add some routes]
const findRoute = compileRouter(router);
const matchAll = compileRouter(router, { matchAll: true });
findRoute("GET", "/path/foo/bar");

compileRouterToString(router, functionName?, opts?)

Compile the router instance into a compact runnable code.

IMPORTANT: Route data must be serializable to JSON (i.e., no functions or classes) or implement the toJSON() method to render custom code or you can pass custom serialize function in options.

Example:

import { createRouter, addRoute } from "rou3";
import { compileRouterToString } from "rou3/compiler";
const router = createRouter();
// [add some routes with serializable data]
const compilerCode = compileRouterToString(router, "findRoute");
// "const findRoute=(m, p) => {}"

License

Published under the MIT license. Made by @pi0 and community 💛


🤖 auto updated with automd

Join libs.tech

...and unlock some superpowers

GitHub

We won't share your data with anyone else.