-
Notifications
You must be signed in to change notification settings - Fork 734
/
Copy pathApolloClient.swift
276 lines (236 loc) · 10.8 KB
/
ApolloClient.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import Foundation
import Dispatch
/// A cache policy that specifies whether results should be fetched from the server or loaded from the local cache.
public enum CachePolicy {
/// Return data from the cache if available, else fetch results from the server.
case returnCacheDataElseFetch
/// Always fetch results from the server.
case fetchIgnoringCacheData
/// Always fetch results from the server, and don't store these in the cache.
case fetchIgnoringCacheCompletely
/// Return data from the cache if available, else return nil.
case returnCacheDataDontFetch
/// Return data from the cache if available, and always fetch results from the server.
case returnCacheDataAndFetch
}
/// A handler for operation results.
///
/// - Parameters:
/// - result: The result of a performed operation. Will have a `GraphQLResult` with any parsed data and any GraphQL errors on `success`, and an `Error` on `failure`.
public typealias GraphQLResultHandler<Data> = (Result<GraphQLResult<Data>, Error>) -> Void
/// The `ApolloClient` class implements the core API for Apollo by conforming to `ApolloClientProtocol`.
public class ApolloClient {
let networkTransport: NetworkTransport
public let store: ApolloStore // <- conformance to ApolloClientProtocol
private let queue: DispatchQueue
private let operationQueue: OperationQueue
public enum ApolloClientError: Error, LocalizedError {
case noUploadTransport
public var errorDescription: String? {
switch self {
case .noUploadTransport:
return "Attempting to upload using a transport which does not support uploads. This is a developer error."
}
}
}
/// Creates a client with the specified network transport and store.
///
/// - Parameters:
/// - networkTransport: A network transport used to send operations to a server.
/// - store: A store used as a local cache. Should default to an empty store backed by an in-memory cache.
public init(networkTransport: NetworkTransport, store: ApolloStore = ApolloStore(cache: InMemoryNormalizedCache())) {
self.networkTransport = networkTransport
self.store = store
queue = DispatchQueue(label: "com.apollographql.ApolloClient")
operationQueue = OperationQueue()
operationQueue.underlyingQueue = queue
}
/// Creates a client with an HTTP network transport connecting to the specified URL.
///
/// - Parameter url: The URL of a GraphQL server to connect to.
public convenience init(url: URL) {
self.init(networkTransport: HTTPNetworkTransport(url: url))
}
fileprivate func send<Operation: GraphQLOperation>(operation: Operation, shouldPublishResultToStore: Bool, context: UnsafeMutableRawPointer?, resultHandler: @escaping GraphQLResultHandler<Operation.Data>) -> Cancellable {
return networkTransport.send(operation: operation) { result in
self.handleOperationResult(shouldPublishResultToStore: shouldPublishResultToStore,
context: context,
result,
resultHandler: resultHandler)
}
}
private func handleOperationResult<Operation>(shouldPublishResultToStore: Bool, context: UnsafeMutableRawPointer?, _ result: Result<GraphQLResponse<Operation>, Error>, resultHandler: @escaping GraphQLResultHandler<Operation.Data>) {
switch result {
case .failure(let error):
resultHandler(.failure(error))
case .success(let response):
// If there is no need to publish the result to the store, we can use a fast path.
if !shouldPublishResultToStore {
do {
let result = try response.parseResultFast()
resultHandler(.success(result))
} catch {
resultHandler(.failure(error))
}
return
}
firstly {
try response.parseResult(cacheKeyForObject: self.cacheKeyForObject)
}.andThen { (result, records) in
if let records = records {
self.store.publish(records: records, context: context).catch { error in
preconditionFailure(String(describing: error))
}
}
resultHandler(.success(result))
}.catch { error in
resultHandler(.failure(error))
}
}
}
}
// MARK: - ApolloClientProtocol conformance
extension ApolloClient: ApolloClientProtocol {
public var cacheKeyForObject: CacheKeyForObject? {
get {
return self.store.cacheKeyForObject
}
set {
self.store.cacheKeyForObject = newValue
}
}
public func clearCache(callbackQueue: DispatchQueue = .main, completion: ((Result<Void, Error>) -> Void)? = nil) {
self.store.clearCache(completion: completion)
}
@discardableResult public func fetch<Query: GraphQLQuery>(query: Query,
cachePolicy: CachePolicy = .returnCacheDataElseFetch,
context: UnsafeMutableRawPointer? = nil,
queue: DispatchQueue = DispatchQueue.main,
resultHandler: GraphQLResultHandler<Query.Data>? = nil) -> Cancellable {
let resultHandler = wrapResultHandler(resultHandler, queue: queue)
// If we don't have to go through the cache, there is no need to create an operation
// and we can return a network task directly
if cachePolicy == .fetchIgnoringCacheData || cachePolicy == .fetchIgnoringCacheCompletely {
return self.send(operation: query, shouldPublishResultToStore: cachePolicy != .fetchIgnoringCacheCompletely, context: context, resultHandler: resultHandler)
} else {
let operation = FetchQueryOperation(client: self, query: query, cachePolicy: cachePolicy, context: context, resultHandler: resultHandler)
self.operationQueue.addOperation(operation)
return operation
}
}
public func watch<Query: GraphQLQuery>(query: Query,
cachePolicy: CachePolicy = .returnCacheDataElseFetch,
queue: DispatchQueue = .main,
resultHandler: @escaping GraphQLResultHandler<Query.Data>) -> GraphQLQueryWatcher<Query> {
let watcher = GraphQLQueryWatcher(client: self,
query: query,
resultHandler: wrapResultHandler(resultHandler, queue: queue))
watcher.fetch(cachePolicy: cachePolicy)
return watcher
}
@discardableResult
public func perform<Mutation: GraphQLMutation>(mutation: Mutation,
context: UnsafeMutableRawPointer? = nil,
queue: DispatchQueue = DispatchQueue.main,
resultHandler: GraphQLResultHandler<Mutation.Data>? = nil) -> Cancellable {
return self.send(operation: mutation,
shouldPublishResultToStore: true,
context: context,
resultHandler: wrapResultHandler(resultHandler, queue: queue))
}
@discardableResult
public func upload<Operation: GraphQLOperation>(operation: Operation,
context: UnsafeMutableRawPointer? = nil,
files: [GraphQLFile],
queue: DispatchQueue = .main,
resultHandler: GraphQLResultHandler<Operation.Data>? = nil) -> Cancellable {
let wrappedHandler = wrapResultHandler(resultHandler, queue: queue)
guard let uploadingTransport = self.networkTransport as? UploadingNetworkTransport else {
assertionFailure("Trying to upload without an uploading transport. Please make sure your network transport conforms to `UploadingNetworkTransport`.")
wrappedHandler(.failure(ApolloClientError.noUploadTransport))
return EmptyCancellable()
}
return uploadingTransport.upload(operation: operation, files: files) { result in
self.handleOperationResult(shouldPublishResultToStore: true,
context: context, result,
resultHandler: wrappedHandler)
}
}
@discardableResult
public func subscribe<Subscription: GraphQLSubscription>(subscription: Subscription,
queue: DispatchQueue = .main,
resultHandler: @escaping GraphQLResultHandler<Subscription.Data>) -> Cancellable {
return self.send(operation: subscription,
shouldPublishResultToStore: true,
context: nil,
resultHandler: wrapResultHandler(resultHandler, queue: queue))
}
}
private func wrapResultHandler<Data>(_ resultHandler: GraphQLResultHandler<Data>?, queue handlerQueue: DispatchQueue) -> GraphQLResultHandler<Data> {
guard let resultHandler = resultHandler else {
return { _ in }
}
return { result in
handlerQueue.async {
resultHandler(result)
}
}
}
private final class FetchQueryOperation<Query: GraphQLQuery>: AsynchronousOperation, Cancellable {
let client: ApolloClient
let query: Query
let cachePolicy: CachePolicy
let context: UnsafeMutableRawPointer?
let resultHandler: GraphQLResultHandler<Query.Data>
private var networkTask: Cancellable?
init(client: ApolloClient, query: Query, cachePolicy: CachePolicy, context: UnsafeMutableRawPointer?, resultHandler: @escaping GraphQLResultHandler<Query.Data>) {
self.client = client
self.query = query
self.cachePolicy = cachePolicy
self.context = context
self.resultHandler = resultHandler
}
override public func start() {
if isCancelled {
state = .finished
return
}
state = .executing
if cachePolicy == .fetchIgnoringCacheData {
fetchFromNetwork()
return
}
client.store.load(query: query) { result in
if self.isCancelled {
self.state = .finished
return
}
switch result {
case .success:
self.resultHandler(result)
if self.cachePolicy != .returnCacheDataAndFetch {
self.state = .finished
return
}
case .failure:
if self.cachePolicy == .returnCacheDataDontFetch {
self.resultHandler(result)
self.state = .finished
return
}
}
self.fetchFromNetwork()
}
}
func fetchFromNetwork() {
networkTask = client.send(operation: query, shouldPublishResultToStore: true, context: context) { result in
self.resultHandler(result)
self.state = .finished
return
}
}
override public func cancel() {
super.cancel()
networkTask?.cancel()
}
}