add conditional middleware middleware example
This commit is contained in:
parent
552ef6fd52
commit
56b2732133
1 changed files with 41 additions and 0 deletions
41
examples/conditional-middleware-middleware.js
Normal file
41
examples/conditional-middleware-middleware.js
Normal file
|
@ -0,0 +1,41 @@
|
|||
|
||||
var http = require('http');
|
||||
var koa = require('..');
|
||||
var app = koa();
|
||||
|
||||
// logger
|
||||
|
||||
function logger(next){
|
||||
return function *(){
|
||||
var start = new Date;
|
||||
yield next;
|
||||
var ms = new Date - start;
|
||||
console.log('%s %s - %s', this.method, this.url, ms);
|
||||
}
|
||||
}
|
||||
|
||||
function ignoreAssets(mw) {
|
||||
return function(next){
|
||||
return function *(){
|
||||
if (/(\.js|\.css|\.ico)$/.test(this.path)) {
|
||||
yield next;
|
||||
} else {
|
||||
yield mw(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
app.use(ignoreAssets(logger));
|
||||
|
||||
// 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){
|
||||
return function *(){
|
||||
this.body = 'Hello World';
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(3000);
|
Loading…
Reference in a new issue