Skip to content

borderless/fetch-router

Repository files navigation

Fetch Router

NPM version NPM downloads Build status Test coverage

Simple routing middleware for fetch.

Installation

npm install @borderless/fetch-router --save

Usage

import { compose } from "throwback";
import { get, post, paramsKey } from "@borderless/fetch-router";

const animals = ["rabbit", "dog", "cat"];

const app = compose([
  get("/pets", function () {
    return new Response(animals.join("\n"));
  }),
  get("/pets/:id", function (req) {
    return new Response(animals[Number(req[paramsKey].id)]);
  }),
]);

Composition

If you need more control, the package exposes the internally used functions: method and use.

  • use(path, fn, options?) - Match an incoming request against Path To RegExp.
  • method(verb, fn) - Match an incoming request against a HTTP method.

Tip: You can recursively mount routes using use() and { end: false }:

const nested = get("/pets", () => new Response("test"));
const app = use("/api", nested, { end: false }); // Allows partial match on `/api/pets`.

TypeScript

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

License

MIT