Skip to content

Simple pathname router that makes zero assumptions about the server

License

Notifications You must be signed in to change notification settings

borderless/router

Repository files navigation

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

About

Simple pathname router that makes zero assumptions about the server

Resources

License

Security policy

Stars

Watchers

Forks

Packages

No packages published