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