teepsllc / BuckoNetworking

iOS Protocol-Oriented Networking in Swift
MIT License
18 stars 3 forks source link

Codable #4

Closed chayelheinsen closed 6 years ago

chayelheinsen commented 6 years ago

This PR updates Bucko to Swift 4 and promotes Codable to be used. SwiftyJSON has been removed and is not required by Bucko. JSONDecodable and JSONDecodableEndpoint have been removed and DecodableEndpoint has been introduced.

Example on how to use DecodableEndpoint:

struct User: Decodable {
  var name: String
  var phoneNumber: String

  enum CodingKeys: String, CodingKey {
    case name
    case phoneNumber = "phone_number"
  }
}

struct UserService: DecodableEndpoint {
  typealias ResponseType = User
  var baseURL: String { return "https://example.com" }
  var path: String { return "/users" }
  var method: HTTPMethod { return .get }
  var body: Parameters { return Parameters() }
  var headers: HTTPHeaders { return HTTPHeaders() }
}

UserService().request { (user, error) in
  guard let user = user else {
    // Do Error
    return
  }

  // Do something with user
}

Using an enum and DecodableEndpoint is possible, however, DecodableEndpoint will require that each case return the same type. If you want each case to respond with a separate Codable type, you can use Endpoint and its request(responseType:, completion:) method.

enum UserService: Endpoint {
  case index

  var baseURL: String { return "https://example.com" }
  var path: String { return "/users" }
  var method: HTTPMethod { return .get }
  var body: Parameters { return Parameters() }
  var headers: HTTPHeaders { return HTTPHeaders() }
}

UserService.index.request(responseType: [User].self) { (users, error) in
  guard let users = users else {
    // Do Error
    return
  }

  // Do something with users
}
chayelheinsen commented 6 years ago

Updated to support Codable typed responses with enums.