Skip to content

Instantly share code, notes, and snippets.

@kcoder666
Created December 28, 2013 12:00
Show Gist options
  • Save kcoder666/8158697 to your computer and use it in GitHub Desktop.
Save kcoder666/8158697 to your computer and use it in GitHub Desktop.
Cache JSON view in nodejs/express app
/**
* viewFunc(req, res, caching) in which caching is a function to return a value
* to be cached.
*
* @param key
* @param req
* @param res
* @param time
* if `time` < 0 then no caching
* if `time` = 0 then caching permanently
* if `time` > 0 then caching within `time` seconds
* @param viewFunc
*/
var cacheView = function(key, req, res, time, viewFunc) {
if (time < 0) {
return viewFunc(req, res, function(){});
}
cache.get(key, function(err, value) {
if (!err && value) {
return res.send(JSON.parse(value));
} else {
viewFunc(req, res, function(newValue) {
if (newValue instanceof Object) newValue = JSON.stringify(newValue);
cache.set(key, newValue);
if (time > 0) cache.expire(key, time);
});
}
});
};
// Example usage
exports.get_all_sources = function(req, res) {
cacheView('sources', req, res, 0, function(req, res, caching) {
var fields = 'name homePage description status lastUpdated';
Source.find({status: 'enabled'}).select(fields).exec(function(err, sources) {
if (err) return res.send(500, {error: err});
var data = {sources: sources};
caching(data);
return res.send(data);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment