Skip to content

Latest commit

Β 

History

History
156 lines (110 loc) Β· 4.02 KB

README.md

File metadata and controls

156 lines (110 loc) Β· 4.02 KB

cover npm version npm downloads bundle JSDocs License

🌳 radix-rapid

✨ Lightweight and fast router for JavaScript based on Radix Tree🌱.

πŸ“ Usage

Install:

# nyxi
nyxi radix-rapid

# pnpm
pnpm i radix-rapid

# npm
npm i radix-rapid

# yarn
yarn add radix-rapid

Import:

// ESM
import { createRouter } from 'radix-rapid'

// CJS
const { createRouter } = require('radix-rapid')

Create a router instance and insert routes:

const router = createRouter(/* options */)

router.insert('/path', { payload: 'this path' })
router.insert('/path/:name', { payload: 'named route' })
router.insert('/path/foo/**', { payload: 'wildcard route' })
router.insert('/path/foo/**:name', { payload: 'named wildcard route' })

Match route to access matched data:

router.lookup('/path')
// { payload: 'this path' }

router.lookup('/path/fooval')
// { payload: 'named route', params: { name: 'fooval' } }

router.lookup('/path/foo/bar/baz')
// { payload: 'wildcard route' }

router.lookup('/')
// null (no route matched for/)

⚑️ Methods

βž• router.insert(path, data)

path can be static or using :placeholder or ** for wildcard paths.

The data object will be returned on matching params. It should be an object like { handler } and not containing reserved keyword params.

πŸ” router.lookup(path)

Returns matched data for path with optional params key if mached route using placeholders.

❌ router.remove(path)

Remove route matching path.

βš™οΈ Options

You can initialize router instance with options:

const router = createRouter({
   strictTrailingSlash: true,
   routes: {
      '/foo': {}
   }
})
  • πŸ›£οΈ routes: An object specifying initial routes to add
  • 🚦 strictTrailingSlash: By default, the router ignores trailing slashes for matching and adding routes. When set to true, matching with trailing slashes is handled differently.

πŸ”Ž Route Matcher

Creates a multi matcher from router tree that can match all routes matching path:

import { createRouter, toRouteMatcher } from 'radix-rapid'

const router = createRouter({
   routes: {
      '/foo': { m: 'foo' }, // Matches /foo only
      '/foo/**': { m: 'foo/**' }, // Matches /foo/<any>
      '/foo/bar': { m: 'foo/bar' }, // Matches /foo/bar only
      '/foo/bar/baz': { m: 'foo/bar/baz' }, // Matches /foo/bar/baz only
      '/foo/*/baz': { m: 'foo/*/baz' } // Matches /foo/<any>/baz
   }
})

const matcher = toRouteMatcher(router)

const matches = matcher.matchAll('/foo/bar/baz')

// [
//   {
//     "m": "foo/**",
//   },
//   {
//     "m": "foo/*/baz",
//   },
//   {
//     "m": "foo/bar/baz",
//   },
// ]

⚑️ Performance

See benchmark.

πŸ“œ License

MIT - Made with πŸ’ž