Skip to content

Instantly share code, notes, and snippets.

@rawrjustin
Created August 24, 2015 23:23
Show Gist options
  • Save rawrjustin/1e35c5998a53a987b23d to your computer and use it in GitHub Desktop.
Save rawrjustin/1e35c5998a53a987b23d to your computer and use it in GitHub Desktop.
Retry Bridge
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