在 KOA 中停止中间件管道执行

Stop middleware pipeline execution in KOA

请问KOA中有没有办法停止中间件管道的执行?

在下面的示例中,我有一个可以以某种方式验证某些内容的中间件。我如何重新编码我的中间件以在验证失败时停止执行?

var koa = require('koa');
var router = require('koa-router')();
var app = koa();

app.use(router.routes());

// middleware
app.use(function *(next){
  var valid = false;
  if (!valid){
    console.log('entered validation')
    this.body = "error"
    return this.body; // how to stop the execution in here
  }
});

// route
router.get('/', function *(next){
  yield next;
  this.body = "should not enter here";
});


app.listen(3000);

我实际上可以将路线更改为:

router.get('/', function *(next){
  yield next;
  if(this.body !== "error")
    this.body = "should not enter here";
});

但是有没有更好的办法呢?或者我遗漏了什么?

This is just an example, in reality my middleware might put a property in the body (this.body.hasErrors = true) and the route would read from that.

同样,我怎样才能停止我的中间件的执行,这样我的路由就不会被执行?在 Express 中,我认为你可以做一个 response.end(虽然不确定)。

中间件按照您将它们添加到应用程序的顺序执行。
您可以选择屈服于下游中间件或尽早发送响应(错误等)。 所以停止中间件流的关键是不屈服。

app.use(function *(next){
  // yield to downstream middleware if desired
  if(doValidation(this)){
    yield next;
  }
  // or respond in this middleware 
  else{
    this.throw(403, 'Validation Error');
  }
});

app.use(function *(next){
  // this is added second so it is downstream to the first generator function
  // and can only reached if upstream middleware yields      
  this.body = 'Made it to the downstream middleware'
});

为清楚起见编辑:

下面我修改了您的原始示例,使其按照我认为的方式工作。

var koa = require('koa');
var router = require('koa-router')();
var app = koa();

// move route handlers below middleware
//app.use(router.routes());

// middleware
app.use(function *(next){
  var valid = false;
  if (!valid){
    console.log('entered validation')
    this.body = "error"
    // return this.body; // how to stop the execution in here
  }
  else{
    yield next;
  }
});

// route
router.get('/', function *(next){
  // based on your example I don't think you want to yield here
  // as this seems to be a returning middleware
  // yield next;
  this.body = "should not enter here";
});

// add routes here
app.use(router.routes());

app.listen(3000);