chibi-router
v0.0.9
Published
A tiny and powerful router
Downloads
3
Readme
Chibi Router
A tiny and powerful router
Install the package via npm
npm install --save-dev chibi-router
Usage
Basic
import {buildRouter} from 'chibi-router';
const router = buildRouter({
'/users/:name/*': ({params: {name}, wildcards}) =>
`<div>This is ${name}. The rest of the matching path is ${wildcards[0]}.</div>`
});
console.log(router('/users/Me/1/2')); // <div>This is Me. The rest of the matching path is 1/2.</div>
Nesting
import {buildRouter} from 'chibi-router';
const childRouter = buildRouter({
'/products/:name': ({params: {name}}) =>
`<div>Product is ${name}</div>`,
'/users/:name': ({params: {name}}) =>
`<div>User is ${name}</div>`
});
const parentRouter = buildRouter({
'/admin/*': ({wildcards}) =>
`<div>This is Admin Page. ${childRouter(wildcards[0])}</div>`
});
console.log(parentRouter('/admin/products/candle'));
// <div>This is Admin Page. <div>Product is candle</div></div>
console.log(parentRouter('/admin/users/Me'));
// <div>This is Admin Page. <div>User is Me</div></div>
Asynchronous Route Callback
import {buildRouter} from 'chibi-router';
const router = buildRouter({
'/' : async () => 'hey Async!',
'/b' : () => 'hey Sync!',
});
(async () => {
console.log(await router('/')); // hey Async!
console.log(await router('/b')); // hey Sync!
})();
Passing values to arguments
import {buildRouter} from 'chibi-router';
const router = buildRouter({
'/' : (_, ...args) => {
console.log(args); // [ 'a', 'b', true, [ 1 ] ]
}
});
router('/', 'a', 'b', true, [1]);