@koex/router
TypeScript icon, indicating that this package has built-in type declarations

1.0.2 • Public • Published

router

NPM version Coverage Status Dependencies Build Status license issues

Simple Router for Koa

Install

$ npm install @koex/router

Usage

// See more in test
import * as router from '@koex/router';

import * as Koa from 'koa';
const app = new Koa();

app.use(router.get('/', async (ctx) => {
  ctx.body = 'home';
}));

app.use(router.get('/health', async (ctx) => {
  ctx.status = 200;
  ctx.body = 'ok';
}));

app.use(router.get('/product/:pid', async (ctx) => {
  ctx.body = ctx.params.pid;
}));

// support middlewares for router
const md5 = crypto.createHash('md5').update('123').digest('hex');

const responseTime = async (ctx, next) => {
  const start = Date.now();
  await next();
  ctx.set('X-Response-Time', Date.now() - start);
};

const requestId = async (ctx, next) => {
  await next();
  const id = md5(ctx.url + Date.now());
  ctx.set('X-Request-Id', id);
};

const handler = async (ctx) => {
  ctx.body = ctx.params.pid + ': ' + ctx.params.cid;
};

app.use(router.get('/product/:pid/:cid', responseTime, requestId, handler));

// fallback
app.use(async (ctx) => {
  ctx.body = {
    name: 'name',
    value: 'value',
  };
});

app.listen(8000, '0.0.0.0', () => {
  console.log('koa server start at port: 8000');
});

Related

Readme

Keywords

none

Package Sidebar

Install

npm i @koex/router

Weekly Downloads

1

Version

1.0.2

License

MIT

Unpacked Size

11.6 kB

Total Files

12

Last publish

Collaborators

  • uniquecolesmith