Skip to content

Instantly share code, notes, and snippets.

@chandan-0
Created March 3, 2022 13:21
Show Gist options
  • Save chandan-0/f33daaf601b22128f4882e8db2cc7407 to your computer and use it in GitHub Desktop.
Save chandan-0/f33daaf601b22128f4882e8db2cc7407 to your computer and use it in GitHub Desktop.
Creating Apollo-Client iOS
import Foundation
import Apollo
class Network {
static let shared = Network()
var apollo: ApolloClient {
// The cache is necessary to set up the store, which we're going to hand to the provider
let cache = InMemoryNormalizedCache()
let store = ApolloStore(cache: cache)
let accessToken = "SET_AUTHORIZATION_TOKEN" // TODO: - "Authorization_TOKEN"
let authPayloads = ["Authorization": "Bearer \(String(describing: accessToken))"]
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = authPayloads
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
let client = URLSessionClient(sessionConfiguration: configuration, callbackQueue: nil)
let provider = NetworkInterceptorProvider(store: store, client: client)
let endpointURL = URL(string: "YOUR_ENDPOINT_URL")!// TODO: - "YOUR_ENDPOINT_URL"
let requestChainTransport = RequestChainNetworkTransport(interceptorProvider: provider, endpointURL: endpointURL)
// Remember to give the store you already created to the client so it
// doesn't create one on its own
return ApolloClient(networkTransport: requestChainTransport, store: store)
}
}
struct NetworkInterceptorProvider: InterceptorProvider {
// These properties will remain the same throughout the life of the `InterceptorProvider`, even though they
// will be handed to different interceptors.
private let store: ApolloStore
private let client: URLSessionClient
init(store: ApolloStore,
client: URLSessionClient) {
self.store = store
self.client = client
}
func interceptors<Operation: GraphQLOperation>(for operation: Operation) -> [ApolloInterceptor] {
return [
MaxRetryInterceptor(),
CacheReadInterceptor(store: self.store),
NetworkFetchInterceptor(client: self.client),
ResponseCodeInterceptor(),
JSONResponseParsingInterceptor(cacheKeyForObject: self.store.cacheKeyForObject),
AutomaticPersistedQueryInterceptor(),
CacheWriteInterceptor(store: self.store)
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment