Skip to content

Instantly share code, notes, and snippets.

@jshier
Last active June 21, 2017 12:53
Show Gist options
  • Save jshier/b4858a4b417217fe8c73 to your computer and use it in GitHub Desktop.
Save jshier/b4858a4b417217fe8c73 to your computer and use it in GitHub Desktop.
Generic Alamofire response serializer with Argo and a custom error type
static func CloudFlareResponseSerializer<T: Decodable where T == T.DecodedType>() -> GenericResponseSerializer<T> {
return GenericResponseSerializer { (request, response, data) -> Result<T> in
guard let validData = data else {
let failureReason = "Tried to decode response with nil data."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(data, CloudFlareError.SerializationError(error: error))
}
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let JSONResult = JSONSerializer.serializeResponse(request, response, validData)
guard case let .Success(responseJSON) = JSONResult else {
return .Failure(data, CloudFlareError.SerializationError(error: JSONResult.error! as NSError))
}
let decodedCloudFlareResponse = CloudFlareResponse.decode(JSON.parse(responseJSON))
guard case let .Success(cloudFlareResponse) = decodedCloudFlareResponse else {
let errorString: String
switch decodedCloudFlareResponse {
case let .TypeMismatch(error):
errorString = error
case let .MissingKey(error):
errorString = error
default:
errorString = "Should never see this."
}
return .Failure(data, CloudFlareError.DecodingError(decodedString: errorString))
}
if !cloudFlareResponse.success {
return .Failure(data, CloudFlareError.ResponseError(response: cloudFlareResponse))
}
let decodedResponseObject = T.decode(cloudFlareResponse.result)
guard case let .Success(responseObject) = decodedResponseObject else {
let errorString: String
switch decodedResponseObject {
case let .TypeMismatch(error):
errorString = error
case let .MissingKey(error):
errorString = error
default:
errorString = "Should never see this."
}
return .Failure(data, CloudFlareError.DecodingError(decodedString: errorString))
}
return .Success(responseObject)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment