Skip to content

Instantly share code, notes, and snippets.

@jordanhamill
Last active December 4, 2016 18:39
Show Gist options
  • Save jordanhamill/0d07ee1162b06b5ffa2d3b7f8bed3185 to your computer and use it in GitHub Desktop.
Save jordanhamill/0d07ee1162b06b5ffa2d3b7f8bed3185 to your computer and use it in GitHub Desktop.
import Foundation
import BrightFutures
public enum HTTPSessionError: Error {
case urlSessionError(Error)
case badResponse
case redirection(Int)
case clientError(Int)
case serverError(Int)
case other(Error)
init(httpErrorStatusCode code: Int) {
switch code {
case 0..<300:
fatalError()
case 300..<400:
self = .redirection(code)
case 400..<500:
self = .clientError(code)
case 500..<600:
self = .serverError(code)
default:
self = .badResponse
}
}
}
public struct HTTPSession {
public static func perform(httpRequest: URLRequest, with session: URLSession)
-> Future<(data: Data, response: HTTPURLResponse), HTTPSessionError> {
let promise = Promise<(data: Data, response: HTTPURLResponse), HTTPSessionError>()
let task = session.dataTask(with: httpRequest) { data, response, error in
guard error == nil else {
promise.failure(.urlSessionError(error!))
return
}
guard let data = data, let response = response as? HTTPURLResponse else {
promise.failure(.badResponse)
return
}
guard 200..<300 ~= response.statusCode else {
promise.failure(HTTPSessionError(httpErrorStatusCode: response.statusCode))
return
}
promise.success((data, response))
}
task.resume()
return promise.future
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment