koa-lite/examples/conditional-middleware.js
Jonathan Ong 98548f0409 conditional middleware need to be .call(this)
just realized this since we removed the top closure. i'm not sure if
there's a better way to solve this, but i'd rather have this
inconvenience than the extra closures.

we should add tests!!!
2013-11-14 21:20:51 -08:00

27 lines
528 B
JavaScript

var koa = require('..');
var app = koa();
// logger
function *logger(next){
var start = new Date;
yield next;
var ms = new Date - start;
console.log('%s %s - %s', this.method, this.url, ms);
}
// sometimes it's useful to apply some
// ad-hoc logic to enable middleware, for
// example ignoring a logger on asset requests:
app.use(function *(next){
if (/(\.js|\.css|\.ico)$/.test(this.path)) {
yield next;
} else {
this.body = 'Hello World';
yield logger.call(this, next);
}
});
app.listen(3000);