Friends

koa

koa-compose 多个中间件合并

下面是使用.call(this,next),将多个中间件合并:

function *random(next) {
  if ('/random' == this.path) {
    this.body = Math.floor(Math.random()*10);
  } else {
    yield next;
  }
};

function *backwards(next) {
  if ('/backwards' == this.path) {
    this.body = 'sdrawkcab';
  } else {
    yield next;
  }
}

function *pi(next) {
  if ('/pi' == this.path) {
    this.body = String(Math.PI);
  } else {
    yield next;
  }
}

function *all(next) {
  yield random.call(this, backwards.call(this, pi.call(this, next)));
}

app.use(all);

更好的合并方式:

var compose = require('koa-compose'),
    session = require('koa-session'),
    jsonp = require('koa-jsonp'),
    serve = require('koa-static'),
    lusca = require('koa-lusca');

module.exports = function(app) {
    return compose([
        lusca(),
        session(app),
        jsonp(),
        serve(app.config.publicFolder)
    ]);
};
Written on September 2, 2015