Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

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

Closed
smagch opened this Issue · 2 comments

2 participants

smagch TJ Holowaychuk
smagch

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

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

TJ Holowaychuk
tj commented

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

TJ Holowaychuk tj closed this in dd33ef2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.