route-maker
For defining, building and matching named routes.
Framework agnostic - just works with strings, can be used in browser and node.js.
Zero dependency, production used.
Install
npm install route-maker
Defining routes
// routes.js of your project root: items: item:
Using routes
Now in router code to get original route string, react for example:
import routes from './routes' <Route = />// Same as:<Route ='/items/:id' />
And for get path with id:
import routes from './routes' <Link = />// Same as:<Link ='/items/123' />
If param was not matched in string, it will become URI parameter:
routes //= '/items?search=phrase'
match
compares pattern and actual path, gives hash with parameters.
// {} // null // {type: 'type_value', b: '123'}
URI params are matched too, notice that :
embedded params are stronger.
// {a: 'a', b: '2', c: '3'}
Positional parameters
Parameters can be passed as plain arguments
routes === '/items/123'routes === '/items/123?param=value'routes === '/api/items/123?param=value'
Positional parameters can be used with hash-provided parameters:
const url = === '/path/1/2'
Options with examples
Options can be set when creating and calling route.
Prefix example:
let path = === '/api/path' === '/api/v2/path' // empty params as first argument, can pass null instead
Can be changed directly:
routeoptionsprefix = 'api' const path = === '/api/path'
Imported constructor can be extended with config
method:
const apiRoute = routelet path = === '/api/path' let path = === '/path'
Prefix and defaults example
const apiRoute = routelet path = path === '/api/v1/path' let path = === '/api/v2/path'
Default values can be dynamically calculated:
let currentUser = {}const userRoute = route let path = currentUsertype = 'customer' === '/customer/path' currentUsertype = 'admin' === '/admin/path'
Options list
url
string, full url if needed. Parameters inside are not allowed.
prefix
string, adds prefix to resulting strings. Parameters inside are allowed.
prependSlash
boolean, default true
, adds slash at the begging of path if it is absent
assign
object, will call Object.assign
on route instances to add them provided properties
defaults
object, default parameters. Works with parameters in prefix. If object value is function then it will be called, result will come to url.