@erect/router
v0.0.5
Published
A Router for Erect
Downloads
14
Readme
Router for Erect
A router thought for Erect.
Usage
Basic
import '@erect/static';
import { mount } from '@erect/core';
import { Router } from '@erect/router';
const router = new Router();
router.get('/', (match, req) => {
req.renderStatic(`
<h2>Home</h2>
`);
);
router.get('/users/:username', { username: 'slug' }, (match, req) => {
req.renderStatic(`
<head>
<title>User ${match.params.username}</title>
</head>
<h2>User ${match.params.username}</h2>
`);
});
Custom param types
import '@erect/static';
import { Router } from '@erect/router';
const router = new Router({
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
year: {
match: /[0-9]{4}/,
parse: (value: string) => parseInt(value),
},
});
router.get('/v/:year/:id/', { year: 'year', id: 'uuid' }, (match, req) => {
req.renderStatic(`
<p>Year is ${match.params.year} and id ${match.params.id}</p>
`);
});
mount(module)
.render(router);
Bundle and Links
Sometimes you want to reuse your routers, Bundle helps you with this task.
Links are also useful and productive.
import '@erect/static';
import { mount } from '@erect/core';
import { Router, Bundle } from '@erect/router';
export const rootRouter = new Router();
// you can wrap your Bundle inside a function to pass
// custom options to your bundle
export const userBundle = new Bundle(
{
list: '/',
single: '/:username',
},
(router, permalinks) => {
const links = {
list: router.link(permalinks.list, (match, req) => {
req.renderStatic(`
<h5>Home</h5>
<p>Go to <a href="${links.single({ username: 'john' })}" data-push>John's Profile</a></p>
`);
}),
single: router.link(permalinks.single, { username: 'slug' }, (match, req) => {
req.renderStatic(`
<h5>Profile ${match.params.username}</h5>
<p>Go back to <a href="${links.list()}" data-push>List</a></p>
`);
})
};
},
);
rootRouter.mount('/', userBundle, {
list: '/users',
single: '/u/:username',
});
mount(module)
.render(rootRouter);