@borderless/router

Simple pathname router that makes zero assumptions about the server

Usage no npm install needed!

<script type="module">
  import borderlessRouter from 'https://cdn.skypack.dev/@borderless/router';
</script>

README

Router

NPM version NPM downloads Build status Build coverage

Simple pathname router that makes zero assumptions about the server.

Installation

npm install @borderless/router --save-dev

Usage

export declare function createRouter(
  routes: string[]
): (pathname: string) => Iterable<Result>;

Exposes a simple createRouter function that accepts a list of routes. It returns a function that accepts the pathname as input and returns an iterable of results. Results are an object containing the route that matched, and list keys and values (if any) that were extracted from dynamic matches.

import { createRouter } from "@borderless/router";

const router = createRouter([
  "a",
  "b",
  "[param]",
  "@[param]",
  "[param1]/[param2]",
]);

const results = Array.from(router("a"));

expect(results).toEqual([
  { route: "a", keys: [], values: [] },
  { route: "[param]", keys: ["param"], values: ["a"] },
]);

Since the result is an iterable, if you only want the first match you can discard the iterable to stop computing results.

const results = router("a");
for (const result of results) {
  console.log(result); //=> { route: "a", keys: [], values: [] }
  break;
}

The routes are pre-sorted to match the most specific routes first (i.e. static routes or most segments), it is not based on the input order. The internal representation is a trie.

TypeScript

This project is written using TypeScript and publishes the definitions directly to NPM.

License

MIT