Skip to content

Commit 2c13ccf

Browse files
Merge pull request #715 from apollographql/add/client-protocol
Add ApolloClientProtocol
2 parents 426818a + aa64e2c commit 2c13ccf

14 files changed

Lines changed: 586 additions & 263 deletions

File tree

Apollo.xcodeproj/project.pbxproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
/* Begin PBXBuildFile section */
1010
54DDB0921EA045870009DD99 /* InMemoryNormalizedCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54DDB0911EA045870009DD99 /* InMemoryNormalizedCache.swift */; };
1111
5AC6CA4322AAF7B200B7C94D /* GraphQLHTTPMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5AC6CA4222AAF7B200B7C94D /* GraphQLHTTPMethod.swift */; };
12+
9B708AAD2305884500604A11 /* ApolloClientProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B708AAC2305884500604A11 /* ApolloClientProtocol.swift */; };
1213
9B95EDC022CAA0B000702BB2 /* GETTransformerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B95EDBF22CAA0AF00702BB2 /* GETTransformerTests.swift */; };
1314
9BA1244A22D8A8EA00BF1D24 /* JSONSerialziation+Sorting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BA1244922D8A8EA00BF1D24 /* JSONSerialziation+Sorting.swift */; };
1415
9BA1245E22DE116B00BF1D24 /* Result+Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BA1245D22DE116B00BF1D24 /* Result+Helpers.swift */; };
@@ -262,6 +263,7 @@
262263
90690D2322433C5900FC2E54 /* Apollo-Target-CacheDependentTests.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Apollo-Target-CacheDependentTests.xcconfig"; sourceTree = "<group>"; };
263264
90690D2422433C8000FC2E54 /* Apollo-Target-PerformanceTests.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Apollo-Target-PerformanceTests.xcconfig"; sourceTree = "<group>"; };
264265
90690D2522433CAF00FC2E54 /* Apollo-Target-TestSupport.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Apollo-Target-TestSupport.xcconfig"; sourceTree = "<group>"; };
266+
9B708AAC2305884500604A11 /* ApolloClientProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApolloClientProtocol.swift; sourceTree = "<group>"; };
265267
9B8D864E22E7A846001F6D50 /* RepoURL.graphql */ = {isa = PBXFileReference; lastKnownFileType = text; path = RepoURL.graphql; sourceTree = "<group>"; };
266268
9B95EDBF22CAA0AF00702BB2 /* GETTransformerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GETTransformerTests.swift; sourceTree = "<group>"; };
267269
9BA1244922D8A8EA00BF1D24 /* JSONSerialziation+Sorting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "JSONSerialziation+Sorting.swift"; sourceTree = "<group>"; };
@@ -627,6 +629,7 @@
627629
isa = PBXGroup;
628630
children = (
629631
9FC750621D2A59F600458D91 /* ApolloClient.swift */,
632+
9B708AAC2305884500604A11 /* ApolloClientProtocol.swift */,
630633
9FC9A9D21E2FD48B0023C4D5 /* GraphQLError.swift */,
631634
9FC750601D2A59C300458D91 /* GraphQLOperation.swift */,
632635
9FCDFD281E33D0CE007519DC /* GraphQLQueryWatcher.swift */,
@@ -1203,6 +1206,7 @@
12031206
9BDE43DD22C6705300FD7C7F /* GraphQLHTTPResponseError.swift in Sources */,
12041207
9FCDFD231E33A0D8007519DC /* AsynchronousOperation.swift in Sources */,
12051208
9BA1244A22D8A8EA00BF1D24 /* JSONSerialziation+Sorting.swift in Sources */,
1209+
9B708AAD2305884500604A11 /* ApolloClientProtocol.swift in Sources */,
12061210
C377CCA922D798BD00572E03 /* GraphQLFile.swift in Sources */,
12071211
9FC9A9CC1E2FD0760023C4D5 /* Record.swift in Sources */,
12081212
9FC4B9201D2A6F8D0046A641 /* JSON.swift in Sources */,

Sources/Apollo/ApolloClient.swift

Lines changed: 95 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -21,22 +21,13 @@ public enum CachePolicy {
2121
/// - 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`.
2222
public typealias GraphQLResultHandler<Data> = (Result<GraphQLResult<Data>, Error>) -> Void
2323

24-
/// The `ApolloClient` class provides the core API for Apollo. This API provides methods to fetch and watch queries, and to perform mutations.
24+
/// The `ApolloClient` class implements the core API for Apollo by conforming to `ApolloClientProtocol`.
2525
public class ApolloClient {
26+
2627
let networkTransport: NetworkTransport
27-
28-
public let store: ApolloStore
29-
30-
public var cacheKeyForObject: CacheKeyForObject? {
31-
get {
32-
return store.cacheKeyForObject
33-
}
34-
35-
set {
36-
store.cacheKeyForObject = newValue
37-
}
38-
}
39-
28+
29+
public let store: ApolloStore // <- conformance to ApolloClientProtocol
30+
4031
private let queue: DispatchQueue
4132
private let operationQueue: OperationQueue
4233

@@ -55,7 +46,7 @@ public class ApolloClient {
5546
///
5647
/// - Parameters:
5748
/// - networkTransport: A network transport used to send operations to a server.
58-
/// - store: A store used as a local cache. Defaults to an empty store backed by an in memory cache.
49+
/// - store: A store used as a local cache. Should default to an empty store backed by an in-memory cache.
5950
public init(networkTransport: NetworkTransport, store: ApolloStore = ApolloStore(cache: InMemoryNormalizedCache())) {
6051
self.networkTransport = networkTransport
6152
self.store = store
@@ -71,99 +62,6 @@ public class ApolloClient {
7162
public convenience init(url: URL) {
7263
self.init(networkTransport: HTTPNetworkTransport(url: url))
7364
}
74-
75-
/// Clears the underlying cache.
76-
/// Be aware: In more complex setups, the same underlying cache can be used across multiple instances, so if you call this on one instance, it'll clear that cache across all instances which share that cache.
77-
///
78-
/// - Returns: Promise which fulfills when clear is complete.
79-
public func clearCache() -> Promise<Void> {
80-
return store.clearCache()
81-
}
82-
83-
/// Fetches a query from the server or from the local cache, depending on the current contents of the cache and the specified cache policy.
84-
///
85-
/// - Parameters:
86-
/// - query: The query to fetch.
87-
/// - cachePolicy: A cache policy that specifies when results should be fetched from the server and when data should be loaded from the local cache.
88-
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
89-
/// - resultHandler: An optional closure that is called when query results are available or when an error occurs.
90-
/// - Returns: An object that can be used to cancel an in progress fetch.
91-
@discardableResult public func fetch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy = .returnCacheDataElseFetch, context: UnsafeMutableRawPointer? = nil, queue: DispatchQueue = DispatchQueue.main, resultHandler: GraphQLResultHandler<Query.Data>? = nil) -> Cancellable {
92-
let resultHandler = wrapResultHandler(resultHandler, queue: queue)
93-
94-
// If we don't have to go through the cache, there is no need to create an operation
95-
// and we can return a network task directly
96-
if cachePolicy == .fetchIgnoringCacheData || cachePolicy == .fetchIgnoringCacheCompletely {
97-
return send(operation: query, shouldPublishResultToStore: cachePolicy != .fetchIgnoringCacheCompletely, context: context, resultHandler: resultHandler)
98-
} else {
99-
let operation = FetchQueryOperation(client: self, query: query, cachePolicy: cachePolicy, context: context, resultHandler: resultHandler)
100-
operationQueue.addOperation(operation)
101-
return operation
102-
}
103-
}
104-
105-
/// Watches a query by first fetching an initial result from the server or from the local cache, depending on the current contents of the cache and the specified cache policy. After the initial fetch, the returned query watcher object will get notified whenever any of the data the query result depends on changes in the local cache, and calls the result handler again with the new result.
106-
///
107-
/// - Parameters:
108-
/// - query: The query to fetch.
109-
/// - fetchHTTPMethod: The HTTP Method to be used.
110-
/// - cachePolicy: A cache policy that specifies when results should be fetched from the server or from the local cache.
111-
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
112-
/// - resultHandler: An optional closure that is called when query results are available or when an error occurs.
113-
/// - Returns: A query watcher object that can be used to control the watching behavior.
114-
public func watch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy = .returnCacheDataElseFetch, queue: DispatchQueue = DispatchQueue.main, resultHandler: @escaping GraphQLResultHandler<Query.Data>) -> GraphQLQueryWatcher<Query> {
115-
let watcher = GraphQLQueryWatcher(client: self, query: query, resultHandler: wrapResultHandler(resultHandler, queue: queue))
116-
watcher.fetch(cachePolicy: cachePolicy)
117-
return watcher
118-
}
119-
120-
/// Performs a mutation by sending it to the server.
121-
///
122-
/// - Parameters:
123-
/// - mutation: The mutation to perform.
124-
/// - fetchHTTPMethod: The HTTP Method to be used.
125-
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
126-
/// - resultHandler: An optional closure that is called when mutation results are available or when an error occurs.
127-
/// - Returns: An object that can be used to cancel an in progress mutation.
128-
@discardableResult public func perform<Mutation: GraphQLMutation>(mutation: Mutation, context: UnsafeMutableRawPointer? = nil, queue: DispatchQueue = DispatchQueue.main, resultHandler: GraphQLResultHandler<Mutation.Data>? = nil) -> Cancellable {
129-
return send(operation: mutation, shouldPublishResultToStore: true, context: context, resultHandler: wrapResultHandler(resultHandler, queue: queue))
130-
}
131-
132-
/// Uploads the given files with the given operation.
133-
///
134-
/// - Parameters:
135-
/// - operation: The operation to send
136-
/// - files: An array of `GraphQLFile` objects to send.
137-
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
138-
/// - completionHandler: The completion handler to execute when the request completes or errors
139-
/// - Returns: An object that can be used to cancel an in progress request.
140-
/// - Throws: If your `networkTransport` does nto also conform to `UploadingNetworkTransport`.
141-
@discardableResult public func upload<Operation: GraphQLOperation>(operation: Operation, context: UnsafeMutableRawPointer? = nil, files: [GraphQLFile], queue: DispatchQueue = .main, resultHandler: GraphQLResultHandler<Operation.Data>? = nil) -> Cancellable {
142-
let wrappedHandler = wrapResultHandler(resultHandler, queue: queue)
143-
guard let uploadingTransport = self.networkTransport as? UploadingNetworkTransport else {
144-
assertionFailure("Trying to upload without an uploading transport. Please make sure your network transport conforms to `UploadingNetworkTransport`.")
145-
wrappedHandler(.failure(ApolloClientError.noUploadTransport))
146-
return EmptyCancellable()
147-
}
148-
149-
return uploadingTransport.upload(operation: operation, files: files) { result in
150-
self.handleOperationResult(shouldPublishResultToStore: true,
151-
context: context, result,
152-
resultHandler: wrappedHandler)
153-
}
154-
}
155-
156-
/// Subscribe to a subscription
157-
///
158-
/// - Parameters:
159-
/// - subscription: The subscription to subscribe to.
160-
/// - fetchHTTPMethod: The HTTP Method to be used.
161-
/// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue.
162-
/// - resultHandler: An optional closure that is called when mutation results are available or when an error occurs.
163-
/// - Returns: An object that can be used to cancel an in progress subscription.
164-
@discardableResult public func subscribe<Subscription: GraphQLSubscription>(subscription: Subscription, queue: DispatchQueue = DispatchQueue.main, resultHandler: @escaping GraphQLResultHandler<Subscription.Data>) -> Cancellable {
165-
return send(operation: subscription, shouldPublishResultToStore: true, context: nil, resultHandler: wrapResultHandler(resultHandler, queue: queue))
166-
}
16765

16866
fileprivate func send<Operation: GraphQLOperation>(operation: Operation, shouldPublishResultToStore: Bool, context: UnsafeMutableRawPointer?, resultHandler: @escaping GraphQLResultHandler<Operation.Data>) -> Cancellable {
16967
return networkTransport.send(operation: operation) { result in
@@ -206,6 +104,95 @@ public class ApolloClient {
206104
}
207105
}
208106

107+
// MARK: - ApolloClientProtocol conformance
108+
109+
extension ApolloClient: ApolloClientProtocol {
110+
111+
public var cacheKeyForObject: CacheKeyForObject? {
112+
get {
113+
return self.store.cacheKeyForObject
114+
}
115+
116+
set {
117+
self.store.cacheKeyForObject = newValue
118+
}
119+
}
120+
121+
public func clearCache() -> Promise<Void> {
122+
return self.store.clearCache()
123+
}
124+
125+
@discardableResult public func fetch<Query: GraphQLQuery>(query: Query,
126+
cachePolicy: CachePolicy = .returnCacheDataElseFetch,
127+
context: UnsafeMutableRawPointer? = nil,
128+
queue: DispatchQueue = DispatchQueue.main,
129+
resultHandler: GraphQLResultHandler<Query.Data>? = nil) -> Cancellable {
130+
let resultHandler = wrapResultHandler(resultHandler, queue: queue)
131+
132+
// If we don't have to go through the cache, there is no need to create an operation
133+
// and we can return a network task directly
134+
if cachePolicy == .fetchIgnoringCacheData || cachePolicy == .fetchIgnoringCacheCompletely {
135+
return self.send(operation: query, shouldPublishResultToStore: cachePolicy != .fetchIgnoringCacheCompletely, context: context, resultHandler: resultHandler)
136+
} else {
137+
let operation = FetchQueryOperation(client: self, query: query, cachePolicy: cachePolicy, context: context, resultHandler: resultHandler)
138+
self.operationQueue.addOperation(operation)
139+
return operation
140+
}
141+
}
142+
143+
public func watch<Query: GraphQLQuery>(query: Query,
144+
cachePolicy: CachePolicy = .returnCacheDataElseFetch,
145+
queue: DispatchQueue = .main,
146+
resultHandler: @escaping GraphQLResultHandler<Query.Data>) -> GraphQLQueryWatcher<Query> {
147+
let watcher = GraphQLQueryWatcher(client: self,
148+
query: query,
149+
resultHandler: wrapResultHandler(resultHandler, queue: queue))
150+
watcher.fetch(cachePolicy: cachePolicy)
151+
return watcher
152+
}
153+
154+
@discardableResult
155+
public func perform<Mutation: GraphQLMutation>(mutation: Mutation,
156+
context: UnsafeMutableRawPointer? = nil,
157+
queue: DispatchQueue = DispatchQueue.main,
158+
resultHandler: GraphQLResultHandler<Mutation.Data>? = nil) -> Cancellable {
159+
return self.send(operation: mutation,
160+
shouldPublishResultToStore: true,
161+
context: context,
162+
resultHandler: wrapResultHandler(resultHandler, queue: queue))
163+
}
164+
165+
@discardableResult
166+
public func upload<Operation: GraphQLOperation>(operation: Operation,
167+
context: UnsafeMutableRawPointer? = nil,
168+
files: [GraphQLFile],
169+
queue: DispatchQueue = .main,
170+
resultHandler: GraphQLResultHandler<Operation.Data>? = nil) -> Cancellable {
171+
let wrappedHandler = wrapResultHandler(resultHandler, queue: queue)
172+
guard let uploadingTransport = self.networkTransport as? UploadingNetworkTransport else {
173+
assertionFailure("Trying to upload without an uploading transport. Please make sure your network transport conforms to `UploadingNetworkTransport`.")
174+
wrappedHandler(.failure(ApolloClientError.noUploadTransport))
175+
return EmptyCancellable()
176+
}
177+
178+
return uploadingTransport.upload(operation: operation, files: files) { result in
179+
self.handleOperationResult(shouldPublishResultToStore: true,
180+
context: context, result,
181+
resultHandler: wrappedHandler)
182+
}
183+
}
184+
185+
@discardableResult
186+
public func subscribe<Subscription: GraphQLSubscription>(subscription: Subscription,
187+
queue: DispatchQueue = .main,
188+
resultHandler: @escaping GraphQLResultHandler<Subscription.Data>) -> Cancellable {
189+
return self.send(operation: subscription,
190+
shouldPublishResultToStore: true,
191+
context: nil,
192+
resultHandler: wrapResultHandler(resultHandler, queue: queue))
193+
}
194+
}
195+
209196
private func wrapResultHandler<Data>(_ resultHandler: GraphQLResultHandler<Data>?, queue handlerQueue: DispatchQueue) -> GraphQLResultHandler<Data> {
210197
guard let resultHandler = resultHandler else {
211198
return { _ in }

0 commit comments

Comments
 (0)