UNPKG

2.65 kBtext/coffeescriptView Raw
1processReadArgs = require './process_read_args'
2modifyObjectInPlace = require './modify_object_in_place'
3
4module.exports = readArrayCache = ($q, providerParams, name, CachedResource, actionConfig) ->
5 ResourceCacheEntry = require('./resource_cache_entry')(providerParams)
6 ResourceCacheArrayEntry = require('./resource_cache_array_entry')(providerParams)
7
8 first = (array, params) ->
9 found = null
10
11 for item in array
12 itemParams = item.$params()
13 if Object.keys(params).every((key) -> itemParams[key] is params[key])
14 found = item
15 break
16
17 found
18
19 ->
20 {params, deferred: cacheDeferred} = processReadArgs($q, arguments)
21 httpDeferred = $q.defer()
22
23 arrayInstance = new Array()
24 arrayInstance.$promise = cacheDeferred.promise
25 arrayInstance.$httpPromise = httpDeferred.promise
26
27 cacheArrayEntry = new ResourceCacheArrayEntry(CachedResource.$key, params).load()
28
29 arrayInstance.$push = (resourceInstance) ->
30 arrayInstance.push(resourceInstance)
31 cacheArrayEntry.addInstances([resourceInstance], false, append: true)
32
33 arrayInstance.$httpPromise.then (instances) ->
34 cacheArrayEntry.addInstances(instances, false)
35
36 readHttp = ->
37 resource = CachedResource.$resource[name](params)
38 resource.$promise.then (response) ->
39 newArrayInstance = new Array()
40
41 response.map (resourceInstance) ->
42 resourceInstance = new CachedResource resourceInstance
43 existingInstance = first(arrayInstance, resourceInstance.$params())
44
45 if existingInstance
46 modifyObjectInPlace(existingInstance, resourceInstance)
47 newArrayInstance.push existingInstance
48 else
49 newArrayInstance.push resourceInstance
50
51 arrayInstance.splice(0, arrayInstance.length, newArrayInstance...)
52
53 cacheDeferred.resolve arrayInstance unless cacheArrayEntry.value
54 httpDeferred.resolve arrayInstance
55 resource.$promise.catch (error) ->
56 cacheDeferred.reject error unless cacheArrayEntry.value
57 httpDeferred.reject error
58
59 if not actionConfig.cacheOnly
60 CachedResource.$writes.flush readHttp
61
62 if cacheArrayEntry.value
63 for cacheInstanceParams in cacheArrayEntry.value
64 cacheInstanceEntry = new ResourceCacheEntry(CachedResource.$key, cacheInstanceParams).load()
65 arrayInstance.push new CachedResource cacheInstanceEntry.value
66
67 # Resolve the promise as the cache is ready
68 cacheDeferred.resolve arrayInstance
69 else if actionConfig.cacheOnly
70 cacheDeferred.reject new Error "Cache value does not exist for params", params
71
72 arrayInstance