@bockit/simple-router
v1.1.0
Published
Universal router, takes a uri as input and calls a handler. Define handlers for patterns or regexes.
Downloads
11
Maintainers
Readme
Simple Router
Define your routes as string or regex patterns that map to functions to call. Intended to be used in universal javascript applications.
One way it could be used is to turn uris into actions to dispatch to stores in a flux architecture.
Installation
npm i @bockit/simple-router
Usage
import SimpleRouter from '@bockit/simple-router'
var router = new SimpleRouter()
router.route('/hello/:name', (req) => {
console.log('hello ' + req.params.name + '!')
})
router.process('/hello/James') // 'hello James!'
API
new SimpleRouter()
Instantiates a new router instance. Has public methods route(pattern, handler)
and process(uri)
.
route(pattern, handler)
Set up a handler function for routes that match a pattern. The pattern can be a regex or a string. If it's a string, we use backbone's route matching patterns.
handler
is a function that takes one argument, the request object.
The request object
The request object has the following properties:
uri
: The uri that was matched.regex
: The regex used to match the route.pattern
: The pattern for this route. If the pattern was a regex, this is null.matched
: The matched groups in theuri
from theregex
.query
: An object representing the query parameters, if available, in theuri
.params
: An object whose keys are the names of the params and splats inpattern
and values are their corresponding values inmatched
. If the pattern was a regex, the keys are indices and the values are the corresponding matched values.
For example, /foo/:bar
matching /foo/quux?beep=boop
becomes:
{
uri: '/foo/quux?beep=boop',
regex: /^/foo/([^/?]+)(?:\?([\s\S]*))?$/,
pattern: '/foo/:bar',
matched: [ 'quux' ],
query: {
beep: 'boop'
},
params: {
bar: 'quux'
}
}
process(uri)
Run a uri
through the routes in a router, calling the handler if a match is found.