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)
}
}