res.locals.use or res.render async parallel middleware option #1120

Closed
smagch opened this Issue May 3, 2012 · 2 comments

Projects

None yet

2 participants

@smagch
smagch commented May 3, 2012

I think a feature like res.locals.use is useful. Let's take a express-mongoose example into this feature implementation.

// mongoose
UserSchema.methods.getLikes = function (callback) {
  this.model('Likes').find({ _user: this._id }, callback);
};

NewsSchema.statics.getLatest = function (callback) {
  this.find({ datePublished: { $gt: new Date(Date.now() - 60000*60) } }, callback);
};

// local 
var getLikes = function(req, res, done){
  req.user.getLikes(function(err, doc){
    if (err) retune done(err);
    res.locals.likes = doc;
    done();
  });
};

var getLatestNews = function(req, res, done){
  News.getLatest(function(err, doc){
    if (err) return done(err);
    res.locals.latestNews = doc;
    done();
  });
}

app.get('/dashboard', function (req, res) {
  res.locals.use(getLikes);
  res.locals.use(getLatestNews);
  res.render('dashboard');
});

or something like

var getLikes = function(req, res, done){
  req.user.getLikes(done);
};

var getLatestNews = function(req, res, done){
  News.getLatest(done);
}

app.get('/dashboard', function (req, res) {
  res.render('dashboard', {
    use: {
      likes: getLikes,
      latestNews: getLatestNews
    }        
  });
});

I think a feature like express-mongoose is easy to implement as Express native now since Express 3.x support view-specific parallel middleware.

smagch commented May 3, 2012

I've pull-requested experimental implementation of this feature. #1121

Owner
tj commented May 3, 2012

+1 from me, might as well have the req/res level equivalent

@tj tj added a commit that closed this issue May 3, 2012
@tj tj Added res.locals.use(). Closes #1120 dd33ef2
@tj tj closed this in dd33ef2 May 3, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment