1 |
|
2 | var modifyObjectInPlace, processReadArgs, readCache;
|
3 |
|
4 | processReadArgs = require('./process_read_args');
|
5 |
|
6 | modifyObjectInPlace = require('./modify_object_in_place');
|
7 |
|
8 | module.exports = readCache = function($q, providerParams, name, CachedResource, actionConfig) {
|
9 | var ResourceCacheEntry;
|
10 | ResourceCacheEntry = require('./resource_cache_entry')(providerParams);
|
11 | return function() {
|
12 | var cacheDeferred, cacheEntry, httpDeferred, instance, params, readHttp, _ref;
|
13 | _ref = processReadArgs($q, arguments), params = _ref.params, cacheDeferred = _ref.deferred;
|
14 | httpDeferred = $q.defer();
|
15 | instance = new CachedResource({
|
16 | $promise: cacheDeferred.promise,
|
17 | $httpPromise: httpDeferred.promise
|
18 | });
|
19 | cacheEntry = new ResourceCacheEntry(CachedResource.$key, params).load();
|
20 | readHttp = function() {
|
21 | var resource;
|
22 | resource = CachedResource.$resource[name].call(CachedResource.$resource, params);
|
23 | resource.$promise.then(function(httpResponse) {
|
24 | modifyObjectInPlace(instance, httpResponse);
|
25 | if (!cacheEntry.value) {
|
26 | cacheDeferred.resolve(instance);
|
27 | }
|
28 | httpDeferred.resolve(instance);
|
29 | if (cacheEntry.dirty) {
|
30 | providerParams.$log.error("unexpectedly setting a clean entry (load) over a dirty entry (pending write)");
|
31 | }
|
32 | return cacheEntry.set(httpResponse, false);
|
33 | });
|
34 | return resource.$promise["catch"](function(error) {
|
35 | if (!cacheEntry.value) {
|
36 | cacheDeferred.reject(error);
|
37 | }
|
38 | return httpDeferred.reject(error);
|
39 | });
|
40 | };
|
41 | if (cacheEntry.dirty) {
|
42 | CachedResource.$writes.processResource(params, readHttp);
|
43 | } else if (!actionConfig.cacheOnly) {
|
44 | readHttp();
|
45 | }
|
46 | if (cacheEntry.value) {
|
47 | angular.extend(instance, cacheEntry.value);
|
48 | cacheDeferred.resolve(instance);
|
49 | } else if (actionConfig.cacheOnly) {
|
50 | cacheDeferred.reject(new Error("Cache value does not exist for params", params));
|
51 | }
|
52 | return instance;
|
53 | };
|
54 | };
|