UNPKG

angular-cached-resource

Version:

An AngularJS module to interact with RESTful resources, even when browser is offline

82 lines (78 loc) 3.27 kB
// Generated by CoffeeScript 1.7.1 var modifyObjectInPlace, processReadArgs, readArrayCache, __slice = [].slice; processReadArgs = require('./process_read_args'); modifyObjectInPlace = require('./modify_object_in_place'); module.exports = readArrayCache = function($q, providerParams, name, CachedResource) { var ResourceCacheArrayEntry, ResourceCacheEntry, first; ResourceCacheEntry = require('./resource_cache_entry')(providerParams); ResourceCacheArrayEntry = require('./resource_cache_array_entry')(providerParams); first = function(array, params) { var found, item, itemParams, _i, _len; found = null; for (_i = 0, _len = array.length; _i < _len; _i++) { item = array[_i]; itemParams = item.$params(); if (Object.keys(params).every(function(key) { return itemParams[key] === params[key]; })) { found = item; break; } } return found; }; return function() { var arrayInstance, cacheArrayEntry, cacheDeferred, cacheInstanceEntry, cacheInstanceParams, httpDeferred, params, readHttp, _i, _len, _ref, _ref1; _ref = processReadArgs($q, arguments), params = _ref.params, cacheDeferred = _ref.deferred; httpDeferred = $q.defer(); arrayInstance = new Array(); arrayInstance.$promise = cacheDeferred.promise; arrayInstance.$httpPromise = httpDeferred.promise; cacheArrayEntry = new ResourceCacheArrayEntry(CachedResource.$key, params).load(); arrayInstance.$httpPromise.then(function(instances) { return cacheArrayEntry.addInstances(instances, false); }); readHttp = function() { var resource; resource = CachedResource.$resource[name](params); resource.$promise.then(function(response) { var newArrayInstance; newArrayInstance = new Array(); response.map(function(resourceInstance) { var existingInstance; resourceInstance = new CachedResource(resourceInstance); existingInstance = first(arrayInstance, resourceInstance.$params()); if (existingInstance) { modifyObjectInPlace(existingInstance, resourceInstance); return newArrayInstance.push(existingInstance); } else { return newArrayInstance.push(resourceInstance); } }); arrayInstance.splice.apply(arrayInstance, [0, arrayInstance.length].concat(__slice.call(newArrayInstance))); if (!cacheArrayEntry.value) { cacheDeferred.resolve(arrayInstance); } return httpDeferred.resolve(arrayInstance); }); return resource.$promise["catch"](function(error) { if (!cacheArrayEntry.value) { cacheDeferred.reject(error); } return httpDeferred.reject(error); }); }; CachedResource.$writes.flush(readHttp); if (cacheArrayEntry.value) { _ref1 = cacheArrayEntry.value; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { cacheInstanceParams = _ref1[_i]; cacheInstanceEntry = new ResourceCacheEntry(CachedResource.$key, cacheInstanceParams).load(); arrayInstance.push(new CachedResource(cacheInstanceEntry.value)); } cacheDeferred.resolve(arrayInstance); } return arrayInstance; }; };