项目作者: bhargavg

项目描述 :
Result'ified URLSession
高级语言: Swift
项目地址: git://github.com/bhargavg/Request.git
创建时间: 2017-06-28T17:04:22Z
项目社区:https://github.com/bhargavg/Request

开源协议:MIT License

下载


Request

A Result’ified URLSession wrapped, designed to be used for CLI scripts

Development Status

Still in pre-alpha

Usage

A simple GET request
  1. let result = get(url: "https://httpbin.org/get")
A simple POST request
  1. let result = post(url: "https://httpbin.org/post")
Analyzing the result
  1. let result = post(url: "https://httpbin.org/post")
  2. switch result {
  3. case let .success(response):
  4. print("Got response: \(response)")
  5. case let .failure(error):
  6. print("Failed with error: \(error)")
  7. }
Parsing the response to a model object
  1. /// Errors
  2. enum InstantiationError: Error {
  3. case sessionError(SessionError)
  4. case invalidResponse
  5. }
  6. /// Model
  7. struct HTTPBinResponse {
  8. let url: String
  9. let origin: String
  10. static func from(response: Response) -> Result<HTTPBinResponse, InstantiationError> {
  11. guard let mayBeDict = try? JSONSerialization.jsonObject(with: response.data) as? [String: Any],
  12. let dict = mayBeDict else {
  13. return .failure(.invalidResponse)
  14. }
  15. guard let origin = dict["origin"] as? String else {
  16. return .failure(.invalidResponse)
  17. }
  18. guard let url = dict["url"] as? String else {
  19. return .failure(.invalidResponse)
  20. }
  21. return .success(HTTPBinResponse(url: url, origin: origin))
  22. }
  23. }
  24. /// Make the request and try to parse the response to model
  25. let result = post(
  26. url: "https://httpbin.org/post",
  27. params: [:],
  28. headers: [:],
  29. body: .jsonArray(["foo", "bar"])
  30. ).mapError({ .sessionError($0) })
  31. .flatMap(HTTPBinResponse.from(response:))
  32. /// Analyze the response
  33. switch result {
  34. case let .success(model):
  35. print("Parsed to model: \(model)")
  36. case let .failure(error):
  37. print("Failed with error: \(error)")
  38. }