Reputation: 13089
Given a nodejs, mongoose, mongodb, expressjs setup, we have permission/security related routes that validate a particular request. For example:
permissionUtils.checkStudentWritePermissions = function(req, res, next){
//load this student from the mongoose db
//ensure the current user has permission to update this student
}
server.put("/api/student/:studentId/enroll",
permissionUtils.checkStudentWritePermissions, function(req, res, next){
//load student from the database, validate the changes
//update student in mongodb, send new version back to user
});
The middleware is useful because we're ensuring the current user has the rights to update the student in every case. (Code re-use etc.) You'll note that in both examples I'm loading the student from the mongodb. Is there an accepted pattern to avoid this double-loading? Some kind of request-cycle cache or a slick way of passing the model around?
Upvotes: 1
Views: 815
Reputation: 5480
There are many different solutions here. I'll try to quickly give you a few.
1) First of all, separate your code to actually fetch (and any pre-processing you need) into a function in a user model. Second, if you don't have a user model, an MVC approach will make your code much easier to follow when it grows. From here, you could easily cache the response on the first call, and just serve it back on the second without re-fetching from the database. Look at something like Memcached or Redis.
2) While it may not be convention, you could pass the object from the middleware into your main function. If you do choose to do this, document what you did clearly so that people in future understand why your middleware is calling next(req, res, obj), and don't 'fix' it by replacing it with just next().
3) A third approach would be to save the object into the res.locals (I believe that's what its called now). These are values that Express keeps for the current request. Saving it there would be similar to a cache, however would only be accessible during that request. On subsequent requests, the object would have to be refetched.
Note that whatever of these options you choose, implementing some sort of cache for commonly accessed objects will, in almost all circumstances, speed up your application.
Upvotes: 1