-
-
Save rawrjustin/1e35c5998a53a987b23d to your computer and use it in GitHub Desktop.
Retry Bridge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RetryBridge: NSObject, ResponseBridge { | |
var requestAttemps = Dictionary<String, Int>() | |
var maxRetryCount = 3 | |
var successfulStatusCodes = Set<Int>(200...299) | |
var badRequestStatusCode = 400 | |
var bypassableErrorStatusCodes = Set<Int>([434]) | |
func process<ReturnType>(endpoint: Endpoint<ReturnType>, response: NSHTTPURLResponse?, responseObject: ResponseObject) -> ProcessResults { | |
print("RETRY RESPONSE:" + "\(response)") | |
print("RETRY OBJECT" + "\(responseObject)") | |
if (response != nil) { | |
if (successfulStatusCodes.contains(response!.statusCode)) { | |
return ProcessResults(true, nil) | |
} else if (badRequestStatusCode == response!.statusCode) { | |
return ProcessResults(true, nil) | |
} else if (!bypassableErrorStatusCodes.contains(response!.statusCode)) { | |
if (responseObject["reason"] != nil) { | |
return ProcessResults(true, nil) | |
} | |
} | |
} | |
incrementAttemptForRequest(endpoint) | |
if shouldAttemptRetry(endpoint) { | |
endpoint.execute(params: endpoint.params, tag:endpoint.tag, success: endpoint.successBlock, failure: endpoint.failureBlock) | |
return ProcessResults(false, nil) | |
} | |
return ProcessResults(true, nil) | |
} | |
func incrementAttemptForRequest<ReturnType>(endpoint: Endpoint<ReturnType>) { | |
if let attempts = self.requestAttemps[retryKeyForEndpoint(endpoint)] as Int! { | |
self.requestAttemps[retryKeyForEndpoint(endpoint)] = attempts + 1 | |
} else { | |
self.requestAttemps[retryKeyForEndpoint(endpoint)] = 1 | |
} | |
} | |
func attempsForRequest<ReturnType>(endpoint: Endpoint<ReturnType>) -> Int { | |
if let attempts = self.requestAttemps[retryKeyForEndpoint(endpoint)] as Int! { | |
return attempts | |
} else { | |
return 0 | |
} | |
} | |
func retryKeyForEndpoint<ReturnType>(endpoint: Endpoint<ReturnType>) -> String { | |
return "\(endpoint.route):\(endpoint.identifier)" | |
} | |
func shouldAttemptRetry<ReturnType>(endpoint: Endpoint<ReturnType>) -> Bool { | |
let attempts = attempsForRequest(endpoint) | |
if attempts <= maxRetryCount { | |
return true | |
} else { | |
return false | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment