node.js - KoaJS middleware and database access -
if had show index users model:
app.use(route.get('/user', list)); function *list() { var res = yield users.find({}); this.body = res; };
is possible put database access part own middleware , call next?
how pass resulting list of users down next middleware? , somehow pass next through route?
so first middleware db access needed, , second middleware presentation?
essentially attach information request context or this
keyword within middleware.
i created screencast on writing middleware might helpful:
http://knowthen.com/episode-4-writing-middleware-in-koajs/
here example of how pass information 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 available here yield next; } app.use(firstmiddleware); app.use(secondmiddleware); app.use(function *(){ // this.session.user available here this.body = this.session.user; }); app.listen(3000);
Comments
Post a Comment