angular-cached-resource
Version:
An AngularJS module to interact with RESTful resources, even when browser is offline
50 lines (46 loc) • 1.73 kB
JavaScript
// Generated by CoffeeScript 1.7.1
var modifyObjectInPlace, processReadArgs, readCache;
processReadArgs = require('./process_read_args');
modifyObjectInPlace = require('./modify_object_in_place');
module.exports = readCache = function($q, providerParams, name, CachedResource) {
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);
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 {
readHttp();
}
if (cacheEntry.value) {
angular.extend(instance, cacheEntry.value);
cacheDeferred.resolve(instance);
}
return instance;
};
};