From 6620447d66a270c5605529f0a51ccfdd5d9769c9 Mon Sep 17 00:00:00 2001 From: Calvin Cestari Date: Wed, 11 Sep 2024 12:12:36 -0700 Subject: [PATCH] enhancement: Set URLRequest cache policy on GET requests (apollographql/apollo-ios-dev#476) --- Sources/Apollo/JSONRequest.swift | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/Sources/Apollo/JSONRequest.swift b/Sources/Apollo/JSONRequest.swift index a7b487a833..5e51727a47 100644 --- a/Sources/Apollo/JSONRequest.swift +++ b/Sources/Apollo/JSONRequest.swift @@ -98,7 +98,8 @@ open class JSONRequest: HTTPRequest { if let urlForGet = transformer.createGetURL() { request.url = urlForGet request.httpMethod = GraphQLHTTPMethod.GET.rawValue - + request.cachePolicy = requestCachePolicy + // GET requests shouldn't have a content-type since they do not provide actual content. request.allHTTPHeaderFields?.removeValue(forKey: "Content-Type") } else { @@ -150,6 +151,22 @@ open class JSONRequest: HTTPRequest { return body } + /// Convert the Apollo iOS cache policy into a matching cache policy for URLRequest. + private var requestCachePolicy: URLRequest.CachePolicy { + switch cachePolicy { + case .returnCacheDataElseFetch: + return .returnCacheDataElseLoad + case .fetchIgnoringCacheData: + return .reloadIgnoringLocalCacheData + case .fetchIgnoringCacheCompletely: + return .reloadIgnoringLocalAndRemoteCacheData + case .returnCacheDataDontFetch: + return .returnCacheDataDontLoad + case .returnCacheDataAndFetch: + return .reloadRevalidatingCacheData + } + } + // MARK: - Equtable/Hashable Conformance public static func == (lhs: JSONRequest, rhs: JSONRequest) -> Bool {