Router
A URL router library.
Installing
npm install url-router --save
Examples
Browser:
import Router from 'url-router'
const router = new Router([
['/path/from', '/resolve/to', { layout: 'main' }],
['/resolve/to/function', () => { console.log('hello') }],
['/resolve/to/object', { template: 'hello' }],
['/in/fact/you/can/resolve/to/any/type', Symbol('hello')],
['/user/:id/profile', '/user/profile'],
['/services/:controller/:method', '/service/$1'],
'/foo/bar',
'/baz/*',
[/^\/article\/(\d+)$/, '/article', 'id', { layout: 'main' }]
])
const route = router.find(location.pathname)
node.js:
const http = require('http')
const Router = require('url-router')
const url = require('url')
const ArticleController = require('./controllers/article')
const router = new Router({
GET: [
['/article/:id', ArticleController.get]
],
POST: [
['/article', ArticleController.create]
],
PUT: [
['/article/:id', ArticleController.update]
],
DELETE: [
['/article/:id', ArticleController.remove]
]
})
http.createServer((req, res) => {
const _url = url.parse(req.url)
const route = router.find(_url.pathname, req.method)
route.result(req, res)
}).listen(8080)
API
new Router(routes)
Create a router.
Routes Definition:
const routes = {
GET: [
route,
...
],
POST: [
route,
...
],
PUT: [
route,
...
],
DELETE: [
route,
...
],
ALL: [
route,
...
]
}
Routes are grouped by different HTTP methods. Routes in group ALL
will be checked by all requests regardless of method.
In the browser-side, there's no need to distinguish HTTP methods, we can simply write:
const routes = [
route,
...
]
It's a shorthand of
const routes = {
ALL: [
route,
...
]
}
Route Definition
const router = new Router([
['/path/from', '/resolve/to', { layout: 'main', requireLogin: true }],
['/resolve/to/function', () => { console.log('hello') }, { layout: 'main', requireLogin: true }],
['/resolve/to/object', { template: 'hello' }, { layout: 'main', requireLogin: true } ],
['/in/fact/you/can/resolve/to/any/type', Symbol('hello')],
['/user/:id/profile', '/user/profile'],
['/services/:controller/:method', '/service/$1'],
'/foo/bar',
'/baz/*',
[/^\/article\/(\d+)$/, '/article', 'id', { layout: 'main' }],
])
router.find(path, method = 'ALL')
Return the route which matchs the path and method, or null if no route matched.
Returns
{
path,
params,
options,
origin
}
See route definition for examples.
Router.log
Enable console log for debugging. Default is false.
Router.log = true
License
MIT