angular-cached-resource
Version:
An AngularJS module to interact with RESTful resources, even when browser is offline
55 lines (51 loc) • 2.06 kB
JavaScript
// Generated by CoffeeScript 1.10.0
var modifyObjectInPlace, processReadArgs, readCache;
processReadArgs = require('./process_read_args');
modifyObjectInPlace = require('./modify_object_in_place');
module.exports = readCache = function($q, providerParams, name, CachedResource, actionConfig) {
var ResourceCacheEntry;
ResourceCacheEntry = require('./resource_cache_entry')(providerParams);
return function() {
var cacheDeferred, cacheEntry, httpDeferred, instance, params, readHttp, ref;
ref = processReadArgs($q, arguments), params = ref.params, cacheDeferred = ref.deferred;
httpDeferred = $q.defer();
instance = new CachedResource({
$promise: cacheDeferred.promise,
$httpPromise: httpDeferred.promise
});
cacheEntry = new ResourceCacheEntry(CachedResource.$key, params).load();
readHttp = function() {
var resource;
resource = CachedResource.$resource[name].call(CachedResource.$resource, params);
resource.$promise.then(function(httpResponse) {
modifyObjectInPlace(instance, httpResponse);
if (!cacheEntry.value) {
cacheDeferred.resolve(instance);
}
httpDeferred.resolve(instance);
if (cacheEntry.dirty) {
providerParams.$log.error("unexpectedly setting a clean entry (load) over a dirty entry (pending write)");
}
return cacheEntry.set(httpResponse, false);
});
return resource.$promise["catch"](function(error) {
if (!cacheEntry.value) {
cacheDeferred.reject(error);
}
return httpDeferred.reject(error);
});
};
if (cacheEntry.dirty) {
CachedResource.$writes.processResource(params, readHttp);
} else if (!actionConfig.cacheOnly) {
readHttp();
}
if (cacheEntry.value) {
angular.extend(instance, cacheEntry.value);
cacheDeferred.resolve(instance);
} else if (actionConfig.cacheOnly) {
cacheDeferred.reject(new Error("Cache value does not exist for params", params));
}
return instance;
};
};