Arash Etemad
Arash Etemad

Reputation: 1909

Set default cache policy apollo swift

Is there any way to set the default cache policy in Apollo framework in swift?

I know I can set cache policy for every fetch request by cachePolicy argument in this way:

Apollo.shared.client.fetch(query: getUser, cachePolicy: CachePolicy.fetchIgnoringCacheData)

But I'm looking for a way to set cache policy in client object for all requests.

Upvotes: 4

Views: 955

Answers (1)

AamirR
AamirR

Reputation: 12198

Looking at the source code, there isn't such method or cachePolicy variable that you can set for ApolloClient.

You can create a singleton Apollo client class, and add your own fetch method with desired cachePolicy, like so

class ApolloManager {

    static let shared = Apollo()

    private var client: ApolloClient!
    var store: ApolloStore { return self.client.store }

    static func configure(url: URL, configuration: URLSessionConfiguration? = nil) {
        let store = ApolloStore(cache: InMemoryNormalizedCache())
        Apollo.shared.client = ApolloClient(networkTransport: HTTPNetworkTransport(url: url, configuration: configuration ?? .default), store: store)
    }

    @discardableResult
    func fetch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy = .fetchIgnoringCacheData, queue: DispatchQueue = .main, resultHandler: OperationResultHandler<Query>? = nil) -> Cancellable? {
        return self.client.fetch(query: query, cachePolicy: cachePolicy, queue: queue, resultHandler: resultHandler)
    }

}

Initializer can be added in didFinishLaunchingWithOptions method of AppDelegate.swift

let url = URL(string: "http://192.168.1.4:2223")!
ApolloManager.configure(url: url)

You can also initialize your client with configuration

let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = ["Authorization": "token"]
ApolloManager.configure(url: url, configuration: configuration)

Usage

ApolloManager.shared.fetch(query: getUser)

Upvotes: 6

Related Questions