Skip to content

Latest commit

 

History

History
84 lines (67 loc) · 2.5 KB

README.md

File metadata and controls

84 lines (67 loc) · 2.5 KB

routes

tests dependencies types module semantic versioning license

Route matcher devised for shared rendering JavaScript applications

install

npm install -S @bicycle-codes/routes

ESM vs CJS

Featuring ESM or CJS versions via package.json exports field.

// esm
import Router from '@bicycle-codes/routes'
// cjs
const Router = require('@bicycle-codes/routes').default

example

Get a router instance

import Router from '@bicycle-codes/routes'
var router = new Router()

Add some routes

router.addRoute('/articles', getArticles);
router.addRoute('/articles/:slug', getArticleBySlug);
router.addRoute('/articles/search/*', searchForArticles);

// can also chain the method calls
router
    .addRoute('/foo', () => {/* ... */})
    .addRoute('/bar', () => {/* ... */})

Find a match

const match = router.match('/articles');
// => RouteMatch

The match object

interface RouteMatch {
    params:Record<string, string>;  // <-- e.g. { slug: 'article-title' }
    splats:string[];
    route:string;
    next?:((...any)=>any)|null;
    action?:(...any)=>any;
    index?:number;
}

You'll get null back if no route matches the provided URL. Otherwise, the route match will provide all the useful information you need inside an object.

Key Description
action The action passed to addRoute as a second argument. Using a function is recommended
next Fall through to the next route, or null if no other routes match
route The route passed to addRoute as the first argument
params An object containing the values for named parameters in the route
splats An object filled with the values for wildcard parameters

License

MIT

fork

This is a fork of ruta3, just adding types.