Created
February 18, 2022 02:28
-
-
Save natpenguin/90dc445a2735a343f8b593929776b541 to your computer and use it in GitHub Desktop.
A extension of Apollo Client for fetching data with async word
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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