I have action that fetches user model from db to check access.
Then I have method that in some cases requires same model.
function checkAccess(req, res, next) {
var data = Data.fetch(req.params._id);
if (data.userId === req.user._id) {
return res.sendStatus(401);
}
return next();
}
Router()
.get('/:_id',
checkAccess,
function (req, res, next) {
var data = Data.fetch(req.params._id);
update(data);
return res.json(data);
});
Question isn't about how to reuse data in exactly that case (the simplest solution I found is use res.local
).
My confusion is about fetching same data from db twice, when it theoretically can be reused.
It isn't heavy request, so caching layer unlikely increase access speed in comparison with access to db. But using cache can introduce many headache with invalidation.
I found that using request-related (res.local
) cache can particularly solve the problem, but it makes my code more verbose and complex. I check every piece of data whether it was fetched, and also should make decision is it possible that this data outdated. Also I pass arguments through several methods to reuse it, so it pollutes my internal API (e.g. when I send email I reuse data needed for rendering email template, so I can't just use mailService.sendInvite(userId)
, but mailService.sendInvite(userId, {user: user, event: event})
).