carson-katri / swift-request

Declarative HTTP networking, designed for SwiftUI
MIT License
731 stars 41 forks source link

Initial `Codable` support #4

Closed carson-katri closed 5 years ago

carson-katri commented 5 years ago

This PR adds support for onObject, which allows Request to decode the response to a concrete type automagically.

It requires that you initialize with the desired type, and then you can use it in the onObject callback:

Request([Todo].self) {
    Url("https://jsonplaceholder.typicode.com/todos")
}
.onObject { (todos: [Todo]?) in
    ...
}
carson-katri commented 5 years ago

I renamed Request to the generic AnyRequest, but also provided the typealias Request for backwards compatibility and convenience.

So now you can use onObject like so:

AnyRequest<[Todo]> {
    Url("https://jsonplaceholder.typicode.com/todos")
}
.onObject { todos in
    ...
}

I was also considering an implementation without typealias, and instead implementing two functions for making requests:

func Request(@RequestBuilder builder: () -> RequestParam) -> AnyRequest<Data>
func Request<ResponseType: Decodable>(_ type: ResponseType.Type, @RequestBuilder builder: () -> RequestParam) -> AnyRequest<ResponseType>

However, with a function you must pass the type as a parameter, which wasn't desirable. It also would require a rewrite of quite a bit of code. It may still be preferable, however.