0.0.4 • Published 5 years ago

@zcorky/koa-router v0.0.4

Weekly downloads
11
License
MIT
Repository
github
Last release
5 years ago

koa-router

NPM version Coverage Status Dependencies Build Status license issues

Simple Router for Koa

Install

$ npm install @zcorky/koa-router

Usage

// See more in test
import * as router from '@zcorky/koa-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