Skip to content

Commit

Permalink
Refactor cache write interceptor
Browse files Browse the repository at this point in the history
* Move chain cancellation check earlier
* Do not expect cache records to be returned
* Only write to cache if cache records were returned
  • Loading branch information
calvincestari committed Jul 24, 2024
1 parent 2d4d14b commit 9f9e586
Showing 1 changed file with 9 additions and 15 deletions.
24 changes: 9 additions & 15 deletions apollo-ios/Sources/Apollo/CacheWriteInterceptor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,12 @@ import ApolloAPI
public struct CacheWriteInterceptor: ApolloInterceptor {

public enum CacheWriteError: Error, LocalizedError {
@available(*, deprecated, message: "Will be removed in a future version.")
case noResponseToParse

case missingCacheRecords

public var errorDescription: String? {
switch self {
case .noResponseToParse:
return "The Cache Write Interceptor was called before a response was received to be parsed. Double-check the order of your interceptors."
case .missingCacheRecords:
return "The Cache Write Interceptor cannot find any cache records. Double-check the order of your interceptors."
}
}
}
Expand All @@ -37,7 +32,11 @@ public struct CacheWriteInterceptor: ApolloInterceptor {
request: HTTPRequest<Operation>,
response: HTTPResponse<Operation>?,
completion: @escaping (Result<GraphQLResult<Operation.Data>, any Error>) -> Void) {


guard !chain.isCancelled else {
return
}

guard request.cachePolicy != .fetchIgnoringCacheCompletely else {
// If we're ignoring the cache completely, we're not writing to it.
chain.proceedAsync(
Expand All @@ -49,25 +48,20 @@ public struct CacheWriteInterceptor: ApolloInterceptor {
return
}

guard
let createdResponse = response,
let cacheRecords = createdResponse.cacheRecords
else {
guard let createdResponse = response else {
chain.handleErrorAsync(
CacheWriteError.missingCacheRecords,
CacheWriteError.noResponseToParse,
request: request,
response: response,
completion: completion
)
return
}

guard !chain.isCancelled else {
return
if let cacheRecords = createdResponse.cacheRecords {
self.store.publish(records: cacheRecords, identifier: request.contextIdentifier)
}

self.store.publish(records: cacheRecords, identifier: request.contextIdentifier)

chain.proceedAsync(
request: request,
response: createdResponse,
Expand Down

0 comments on commit 9f9e586

Please sign in to comment.