Skip to content

Instantly share code, notes, and snippets.

@alexrothenberg
Created December 19, 2014 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexrothenberg/8d50d3302ebe234e94cf to your computer and use it in GitHub Desktop.
Save alexrothenberg/8d50d3302ebe234e94cf to your computer and use it in GitHub Desktop.
Simple caching for angular.js
"use strict";
angular.module('gatewayApp')
.factory('Cache', [function(){
var cache = {};
var _get = function(key) {
var cacheHit = cache[key];
if (_exists(cacheHit) && _notExpired(cacheHit)) {
return cacheHit.value;
} else {
return null;
}
}
var _exists = function(cacheHit) {
return cacheHit !== undefined;
}
var _notExpired = function(cacheHit) {
return cacheHit.expiry > new Date();
}
// hardcoded 1 hour expiry. Would be nice to make configurable
var _set = function(key, value) {
cache[key] = {
expiry: moment().add('hour', 1).toDate(),
value: value
}
return value;
}
var get = function(key, getterFn) {
var cacheHit = _get(key);
if (cacheHit !== null) {
// console.log("cache hit: " + key, cacheHit);
return cacheHit;
} else {
// console.log("cache miss: " + key);
var value = getterFn()
_set(key, value);
return value;
}
}
var invalidate = function(key) {
if (key === undefined) {
cache = {}; // invalidate everything
} else {
delete cache[key]
}
}
return {
get: get,
invalidate: invalidate
}
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment