0

If I had this to show an index for a users model:

app.use(route.get('/user', list));

function *list() {
  var res = yield users.find({});
  this.body = res;
};

Is it possible to put the database access part into its own middleware and then call next?

How could you pass the resulting list of users down to the next middleware? And somehow pass next through the route?

So the first middleware is any DB access needed, and the second middleware is presentation?

Dolbery
  • 185
  • 1
  • 12

1 Answers1

1

Essentially you attach the information to the request context or the this keyword within the middleware.

I created a screencast on writing middleware that might be helpful:

http://knowthen.com/episode-4-writing-middleware-in-koajs/

Here is an example of how you would pass information to downstream middleware.

let koa   = require('koa'),
    users = require('./users'),
    app   = koa();

function *firstMiddleWare (next) {
  this.session = {
    user: yield users.find({});
  }
  yield next;
}

function *secondMiddleware (next) {
  // this.session.user is available here
  yield next;
}

app.use(firstMiddleWare);
app.use(secondMiddleware);

app.use(function *(){
  // this.session.user is available here as well
  this.body = this.session.user;
});

app.listen(3000);
James Moore
  • 1,881
  • 14
  • 18