lark-router

2.3.1 • Public • Published

lark-router

Router for lark based on koa 2.0

NPM version build status Test coverage NPM downloads

Install

$ npm install --save lark-router

Get started

Lark-Router is a flexible and easy-to-use url router tool, compatible with native http apps, express apps and koa(v2) apps.

  • http apps
const router = new LarkRouter();

router.get('/foo/bar', (req, res) => res.end("/foo/bra requested!"));
router.on('error', (error, req, res) => {
    res.statusCode = 500;
    res.end(error.message);
});

http.createServer(router.routes()).listen(3000);
  • koa apps
const router = new LarkRouter();
const app    = new Koa();

router.get('/foo/bar', async (ctx, next) => {
    ctx.body = '/foo/bar requested!';
    await next();
});
router.on('error', (error, ctx, next) => {
    ctx.statusCode = 500;
    ctx.body = error.message;
    return next();
});

app.use(router.routes()).listen(3000);

Params

See path-to-regexp. Params object is bind to the first argument of the app processor.

router.get('/:foo/:bar', (ctx, next) => { console.log(ctx.params); }); // ===> { foo: xxx, bar: xxx }
router.get(/^\/(\d+)\/(\w+)$/, (ctx, next) => { console.log(ctx.params); }); // ===> { 0: xxx, 1: xxx}

all, other, routed

Lark router has 3 special methods.

  • all: match all requests
router.all('/foo/bar', handler);  // ===> response to GET/POST/DELETE/...  /foo/bar
  • other: match all unmatched requests
router.other(/.*/, response404notfound); // ===> response to GET/POST/DELETE/...  /foo/bar if no other route matched
  • routed: match all matched requests
router.routed('/foo/bar', () => console.log('/foo/bar has been routed')); // ===> response to GET/POST/DELETE/...  /foo/bar if some routes matched

Nesting

You could nest routers together:

mainRouter.all('/api', apiRouter);

Async processors

For async processors, return promises.

router.get('/', () => new Promise(...));
router.get('/foo', async () => { ... });

Readme

Keywords

Package Sidebar

Install

npm i lark-router

Weekly Downloads

24

Version

2.3.1

License

MIT

Last publish

Collaborators

  • mdemo
  • zezhou
  • viringbells