Skip to content

koexjs/router

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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