2.3.1 • Published 6 years ago

lark-router v2.3.1

Weekly downloads
8
License
MIT
Repository
github
Last release
6 years ago

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 () => { ... });
2.3.1

6 years ago

2.2.1

7 years ago

2.2.0

7 years ago

2.1.1

7 years ago

2.1.0

7 years ago

2.0.0

7 years ago

1.2.0

7 years ago

1.1.2

8 years ago

1.1.1

8 years ago

1.1.0

8 years ago

1.0.1

8 years ago

1.0.2

8 years ago

0.5.0

8 years ago

1.0.0

8 years ago

0.4.3

9 years ago

0.4.2

9 years ago

0.4.1

9 years ago

0.4.0

9 years ago

0.3.0

9 years ago

0.2.1

9 years ago

0.1.0

9 years ago