2. Recap: Promises
createMagicPromise().then { reply in
if reply.response.statusCode != 200 {
throw RESTError.badResponse(reply.response)
}
// 🤔 : Still need to validate the content type.
return JSON.parse(data: reply.data)
}.then { json in
return User(serialized: json)
}.then { user in
// Do something with the user object.
}.fail { error in
// Don’t handle errors like this when being outside of keynote.
fatalError("FIXME: Handle error: (error)")
}.done()
3. URLSession + Promises
typealias Reply = (response: URLResponse,
data: Data)
// I really don’t have a better name.
protocol RESTful {
func get(url: URL) -> Promise<Reply>
}
7. How to Test?
extension URLSession: RESTful {
func get(url: URL) -> Promise<Reply> {
/* TODO: Use
* URLSession.dataTask(with:, completionHandler:)
*/
fatalError("Unimplemented.")
}
}
// Looks good, no? No, I don’t want to set up an HTTP server.
10. Testing the Protocol
class MockSession: URLSessionLike {
internal func dataTask(with url: URL,
completionHandler: @escaping
URLSessionLike.Completion)
-> URLSessionDataTask
{
DispatchQueue.main.async {
let error = URLError(.notConnectedToInternet)
completionHandler(nil, nil, error)
}
}
}
/* Later you will only mock RESTful things and return
* Promises directly. */