angular-cached-resource
Version:
An AngularJS module to interact with RESTful resources, even when browser is offline
109 lines (97 loc) • 3.3 kB
JavaScript
// Generated by CoffeeScript 1.7.1
var Cache, localStorage;
localStorage = window.localStorage;
Cache = (function() {
Cache.prototype.memoryCache = {};
function Cache(_arg) {
this.$log = _arg.$log, this.localStoragePrefix = _arg.localStoragePrefix;
}
Cache.prototype.getItem = function(key, fallbackValue) {
var item, out;
key = this._buildKey(key);
item = this.memoryCache[key];
if (item == null) {
item = localStorage.getItem(key);
}
out = item != null ? angular.fromJson(item) : fallbackValue;
this.$log.debug("CACHE GET: " + key, out);
return out;
};
Cache.prototype.setItem = function(key, value) {
var stringValue;
key = this._buildKey(key);
stringValue = angular.toJson(value);
try {
localStorage.setItem(key, stringValue);
if (this.memoryCache[key] != null) {
delete this.memoryCache[key];
}
} catch (_error) {
this.memoryCache[key] = stringValue;
}
this.$log.debug("CACHE PUT: " + key, angular.fromJson(angular.toJson(value)));
return value;
};
Cache.prototype.clear = function(_arg) {
var cacheKey, cacheKeys, exceptFor, exception, i, key, skipKey, where, _i, _j, _k, _l, _len, _len1, _len2, _ref, _ref1, _results, _results1;
_ref = _arg != null ? _arg : {}, key = _ref.key, exceptFor = _ref.exceptFor, where = _ref.where;
if (where && exceptFor) {
return this.$log.error("Using where and exceptFor arguments at once in clear() method is forbidden!");
}
if (exceptFor) {
if (exceptFor == null) {
exceptFor = [];
}
cacheKeys = [];
for (i = _i = 0, _ref1 = localStorage.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
cacheKey = localStorage.key(i);
if (!this._cacheKeyHasPrefix(cacheKey, key)) {
continue;
}
skipKey = false;
for (_j = 0, _len = exceptFor.length; _j < _len; _j++) {
exception = exceptFor[_j];
if (!(this._cacheKeyHasPrefix(cacheKey, exception))) {
continue;
}
skipKey = true;
break;
}
if (skipKey) {
continue;
}
cacheKeys.push(cacheKey);
}
_results = [];
for (_k = 0, _len1 = cacheKeys.length; _k < _len1; _k++) {
cacheKey = cacheKeys[_k];
_results.push(localStorage.removeItem(cacheKey));
}
return _results;
} else {
_results1 = [];
for (_l = 0, _len2 = where.length; _l < _len2; _l++) {
cacheKey = where[_l];
_results1.push(localStorage.removeItem(this._buildKey(cacheKey)));
}
return _results1;
}
};
Cache.prototype._buildKey = function(key) {
return "" + this.localStoragePrefix + key;
};
Cache.prototype._cacheKeyHasPrefix = function(cacheKey, prefix) {
var index, nextChar;
if (prefix == null) {
return cacheKey.indexOf(this.localStoragePrefix) === 0;
}
prefix = this._buildKey(prefix);
index = cacheKey.indexOf(prefix);
nextChar = cacheKey[prefix.length];
return index === 0 && ((nextChar == null) || (nextChar === '?' || nextChar === '/'));
};
return Cache;
})();
module.exports = function(providerParams) {
return new Cache(providerParams);
};