Skip to content

Instantly share code, notes, and snippets.

@natpenguin
Created February 18, 2022 02:28
Show Gist options
  • Save natpenguin/90dc445a2735a343f8b593929776b541 to your computer and use it in GitHub Desktop.
Save natpenguin/90dc445a2735a343f8b593929776b541 to your computer and use it in GitHub Desktop.
A extension of Apollo Client for fetching data with async word
import Foundation
import Apollo
public extension ApolloClient {
func asyncFetch<Q: GraphQLQuery>(query: Q, cachePolicy: CachePolicy, queue: DispatchQueue) async throws -> Q.Data {
try await withCheckedThrowingContinuation({ [weak self] continuation in
guard let self = self else {
continuation.resume(throwing: NSError(domain: "Apollo.NoSelfError", code: -1, userInfo: nil))
return
}
self.fetch(query: query, cachePolicy: cachePolicy, queue: queue) { result in
switch result {
case .success(let result):
if let data = result.data {
continuation.resume(returning: data)
} else if let error = result.errors?.first {
continuation.resume(throwing: error)
} else {
continuation.resume(throwing: NSError(domain: "Apollo.UnhandledError", code: -2, userInfo: nil))
}
case .failure(let error):
continuation.resume(throwing: error)
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment