koa-lite/examples/compose.js

51 lines
798 B
JavaScript
Raw Normal View History

2013-08-17 07:15:57 +00:00
var compose = require('koa-compose');
var koa = require('..');
var app = koa();
// x-response-time
function responseTime(){
return function *responseTime(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
2013-08-17 07:15:57 +00:00
}
}
// logger
function logger(){
return function* logger(next){
var start = new Date;
yield next;
var ms = new Date - start;
console.log('%s %s - %s', this.method, this.url, ms);
2013-08-17 07:15:57 +00:00
}
}
// response
function respond() {
return function* respond(next){
yield next;
if ('/' != this.url) return;
this.body = 'Hello World';
2013-08-17 07:15:57 +00:00
}
}
// composed middleware
function all() {
return compose([
responseTime(),
logger(),
respond()
]);
}
app.use(all());
app.listen(3000);