From 511b76aa4bd7ee85917fd5913214c81286088927 Mon Sep 17 00:00:00 2001 From: Calvin Cestari Date: Tue, 10 Sep 2024 17:16:51 -0700 Subject: [PATCH] Set URLRequest cache policy on GET requests --- apollo-ios/Sources/Apollo/JSONRequest.swift | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/apollo-ios/Sources/Apollo/JSONRequest.swift b/apollo-ios/Sources/Apollo/JSONRequest.swift index a7b487a83..5e51727a4 100644 --- a/apollo-ios/Sources/Apollo/JSONRequest.swift +++ b/apollo-ios/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 {