-
Notifications
You must be signed in to change notification settings - Fork 738
/
Copy pathCacheWriteInterceptor.swift
78 lines (66 loc) · 2.17 KB
/
CacheWriteInterceptor.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import Foundation
#if !COCOAPODS
import ApolloAPI
#endif
/// An interceptor which writes data to the cache, following the `HTTPRequest`'s `cachePolicy`.
public struct CacheWriteInterceptor: ApolloInterceptor {
public enum CacheWriteError: Error, LocalizedError {
@available(*, deprecated, message: "Will be removed in a future version.")
case noResponseToParse
case missingCacheRecords
public var errorDescription: String? {
switch self {
case .noResponseToParse:
return "The Cache Write Interceptor was called before a response was received to be parsed. Double-check the order of your interceptors."
case .missingCacheRecords:
return "The Cache Write Interceptor cannot find any cache records. Double-check the order of your interceptors."
}
}
}
public let store: ApolloStore
public var id: String = UUID().uuidString
/// Designated initializer
///
/// - Parameter store: The store to use when writing to the cache.
public init(store: ApolloStore) {
self.store = store
}
public func interceptAsync<Operation: GraphQLOperation>(
chain: any RequestChain,
request: HTTPRequest<Operation>,
response: HTTPResponse<Operation>?,
completion: @escaping (Result<GraphQLResult<Operation.Data>, any Error>) -> Void) {
guard request.cachePolicy != .fetchIgnoringCacheCompletely else {
// If we're ignoring the cache completely, we're not writing to it.
chain.proceedAsync(
request: request,
response: response,
interceptor: self,
completion: completion
)
return
}
guard
let createdResponse = response,
let cacheRecords = createdResponse.cacheRecords
else {
chain.handleErrorAsync(
CacheWriteError.missingCacheRecords,
request: request,
response: response,
completion: completion
)
return
}
guard !chain.isCancelled else {
return
}
self.store.publish(records: cacheRecords, identifier: request.contextIdentifier)
chain.proceedAsync(
request: request,
response: createdResponse,
interceptor: self,
completion: completion
)
}
}