Wednesday 30 March 2016

Loading resources in middleware?

My routes are set up something like this:app.get('/blah/:id', middleware.middleware, controller.get);app.post('/blah/:id', middleware.middleware, controller.update);In my middleware, I load in my resource:module.exports.middleware= function(req, res, next){ Resource.findOne({ _id : req.params.id}, function(err, resource){ if (err){ return res.status(500).json(blahblabhblaha); } if (!resource){ return res.status(404).json(blahblabhblaha); } if (authorization condition fails){ return res.status(401).json(blahblabhblaha); } //more condition checking, etc res.locals.resource = resource; return next(); }); }; This is nice for me because I can handle all of the authorization and stuff in one fell swoop. It also cleans up my controllers considerably. The problem is that I can't use mongo's projections this way, because the controllers need different parts of the resource. Is there anyway I can get around this without resorting to having my controllers make database calls?

Submitted March 30, 2016 at 08:12AM by topdeckerino

No comments:

Post a Comment