Skip to content

Instantly share code, notes, and snippets.

@michael
Created August 22, 2015 15:19
Show Gist options
  • Save michael/7ac366c9f011a9c96d14 to your computer and use it in GitHub Desktop.
Save michael/7ac366c9f011a9c96d14 to your computer and use it in GitHub Desktop.
// Slow function that we want to cache
getResourcesMap = function(cb) {
...
cb(null, res);
}
// Making a new cache by passing slow function to
// the constructor and the refresh interval
var resourceMapCache = new APICache(getResourceMap, 5000);
// Express endpoint
var getResources = function(req, res, next) {
resourceMapCache.get(function(err, resourceMap) {
res.json(resourceMap);
});
};
// APICache implementation
// -----------------
var APICache = function(fn, refreshInterval) {
this.fn = fn;
this.refreshInterval;
this.cachedValue = null;
};
APICache.prototype.initialize = function(cb) {
this.updateCache(cb);
// Continue to refresh cache
setInterval(this.updateCache.bind(this), this.refreshInterval);
};
APICache.prototype.updateCache = function(cb) {
var self = this;
this.fn(function(err, res) {
self.cachedValue = res;
cb(err);
});
};
APICache.prototype.get = function(cb) {
var self = this;
if (this.cachedValue) {
cb(null, this.cachedValue);
} else {
this.initialize(function() {
cb(null, self.cachedValue);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment