Skip to content

A minimal async Request → Response router powered by URL Pattern API magic ✨

License

Notifications You must be signed in to change notification settings

dbushell/velocirouter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

42 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🦕 VelociRouter

JSR NPM

A minimal async RequestResponse router powered by URL Pattern API magic ✨

Usage

Route handles are attached using an HTTP method name:

const router = new Router();

router.get('*', () => {
  return new Response('Hello, World!');
});

Router method names like get and post are lower case.

Requests are passed through all matching handles in the order they were attached.

The first parameter is a URL Pattern API input. String inputs are matched against the URL pathname. Object inputs are used to match parts of the URL. The second parameter is a handle function.

router.get({pathname: '/hello/:name'}, ({match}) => {
  const {name} = match.pathname.groups;
  return new Response(`Hello ${name}!`);
});

For fastest performance provide a full URLPattern instance:

router.get(new URLPattern({pathname: '/:slug([\w-] )'}), () => {
  // Pattern matches [a-zA-Z0-9_-]
});

Options

The Router class accepts the following configuration:

const router = new Router({
  onError: (error, request) => {
    console.error(error);
    return new Response(null {status: 500});
  },
  onNoMatch: (request) => {
    return new Response(null, {status: 404});
  },
  autoHead: false
});

onError - a fallback handle when an error is thrown. Default is a 500 response.

onNoMatch - a fallback handle when no response is returned from any matching routes. Default is a 404 response.

autoHead - automatically generate corresponding HEAD handles for any GET handles attached. Default is true.

Handle Functions

The handle function receives a props object as the only argument.

The props object includes:

  • request - the Request object matching the route pattern
  • response - the Response object returned by a previous handle (or undefined)
  • match - the URLPatternResult
  • platform - any platform specific data
  • stopPropagation - a function to stop any further handles being called

Handle Return Values

If the handle returns void or undefined it has no effect on the route. Any previous handle's Response is used.

If the handle returns null any previous handles are ignored. The route will be handled by onNoMatch unless any following handles exist.

If the handles returns a Response that becomes the route's response unless any following handles have an effect.

Handles can return an object: {request, response}. The request property changes the routes Request passed to any following handles. The optional response property follows the same rules above.

If an uncaught error is thrown inside a handle the onError option is used.

Middleware

Middleware is added with the use method:

router.use(({request}) => {
  console.log(`[${request.method}] ${request.url}`);
});

Handles attached with use match all requests. They are executed in order before all other route handles.

A special all handle will match all HTTP methods with a pattern:

router.all({pathname: '*'}, ({response}) => {
  if (response) {
    response.headers.set('x-powered-by', 'velocirouter');
  }
});

Handles attached with all are executed in order alongside route handles after any middleware.

Notes

Only Deno and Chromium based browsers have URL Pattern API support right now. Other runtimes like Bun and Node require a polyfill.

Inspired by Polka and Hono.


MIT License | Copyright © 2024 David Bushell

About

A minimal async Request → Response router powered by URL Pattern API magic ✨

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published