/
MaxRetryInterceptor.swift
61 lines (51 loc) 路 1.64 KB
/
MaxRetryInterceptor.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import Foundation
#if !COCOAPODS
import ApolloAPI
#endif
/// An interceptor to enforce a maximum number of retries of any `HTTPRequest`
public class MaxRetryInterceptor: ApolloInterceptor {
private let maxRetries: Int
private var hitCount = 0
public var id: String = UUID().uuidString
public enum RetryError: Error, LocalizedError {
case hitMaxRetryCount(count: Int, operationName: String)
public var errorDescription: String? {
switch self {
case .hitMaxRetryCount(let count, let operationName):
return "The maximum number of retries (\(count)) was hit without success for operation \"\(operationName)\"."
}
}
}
/// Designated initializer.
///
/// - Parameter maxRetriesAllowed: How many times a query can be retried, in addition to the initial attempt before
public init(maxRetriesAllowed: Int = 3) {
self.maxRetries = maxRetriesAllowed
}
public func interceptAsync<Operation: GraphQLOperation>(
chain: RequestChain,
request: HTTPRequest<Operation>,
response: HTTPResponse<Operation>?,
completion: @escaping (Result<GraphQLResult<Operation.Data>, Error>) -> Void) {
guard self.hitCount <= self.maxRetries else {
let error = RetryError.hitMaxRetryCount(
count: self.maxRetries,
operationName: Operation.operationName
)
chain.handleErrorAsync(
error,
request: request,
response: response,
completion: completion
)
return
}
self.hitCount += 1
chain.proceedAsync(
request: request,
response: response,
interceptor: self,
completion: completion
)
}
}