Radix Router
A router implemented using a Radix Tree (aka compact Prefix Tree).
This router has support for placeholders and wildcards.
Installation
npm install --save radix-router
better yet
yarn add radix-router
Usage
new RadixRouter(options)
- Creates a new instance of a router. The options
object is optional.
Possible parameters for the options
object:
strict
- Setting this option to true
will force lookups to match exact paths (trailing slashes will not be ignored). Defaults to false
.
insert(path, data)
- Adds the given path to the router and associates the given data with the path.
lookup(path)
- Performs a lookup of the path. If there is a match, the data associated with the route is returned.
delete(path)
- Deletes the path from the router.
startsWith(prefix)
- Returns a map of all routes starting with the given prefix and the data associated with them.
Example
const RadixRouter = require('radix-router');
let router = new RadixRouter({
strict: true
});
router.insert('/api/v1/route', {
much: 'data'
});
router.insert('/api/v2/**', {
such: 'wildcard'
});
router.insert('/api/v1/other-route/:id', {
so: 'placeholder',
much: 'wow'
});
router.lookup('/api/v1/route');
// returns {
// path: '/api/v1/route',
// data: {
// much: 'data'
// }
// }
router.lookup('/api/v2/anything/goes/here');
// returns {
// path: '/api/v2/anything/goes/here',
// data: {
// such: 'wildcard'
// }
// }
router.lookup('/api/v1/other-route/abcd');
// returns {
// path: '/api/v1/other-route/abcd',
// data: {
// so: 'placeholder',
// much: 'wow'
// },
// params: {
// id: 'abcd'
// }
// }
// remove route
router.delete('/api/v2/**');
router.lookup('/api/v2/anything/goes/here');
// returns {
// path: '/api/v2/anything/goes/here',
// data: null
// }
route.startsWith('/api')
// returns {
// '/api/v1/route': {
// much: 'data'
// },
// '/api/v1/other-route/:id': {
// so: 'placeholder',
// much: 'wow'
// }
// }