danielsaidi / ApiKit

ApiKit is a Swift SDK that helps you integrate with any REST API.
MIT License
51 stars 3 forks source link

Allow custom decoders to be used #6

Closed jmg-duarte closed 1 week ago

jmg-duarte commented 5 months ago

By default JSONDecoder does not support dates in the ISO8601, the serialization strategy needs to be changed with something like the following:

let decoder: JSONDecoder = {
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .iso8601
    return decoder
}()

However, it's not possible to do so using ApiKit since the decoders used are default and non customizable, leading to a bit extra code:

return try await URLSession.shared.fetch(
    WhatsOnRequest.Feed(whatsOn: feed, accessToken: accessToken),
    from: environment
)

I don't mind the extra code, but it does defeat the purpose of using a request here.

let result = try await URLSession.shared.fetch(
    WhatsOnRequest.Feed(whatsOn: feed,  accessToken: accessToken).route,
    in: environment
)
return try decoder.decode([Event].self, from: result.data)

This would also side step needing to use CodingKeys when you know the target API uses snake case (as it is also my case). But I don't think there is something like CodingKeys for values (if there are, by all means, let me know!).

danielsaidi commented 4 months ago

Hi @jmg-duarte

Sorry for the late reply on this issue.

Do you think providing static encoder/decoder instances would help?

jmg-duarte commented 4 months ago

No worries about the late response.

I think it would make more sense to have:

    /// Fetch a decodable item with the provided request.
    func fetchItem<T: Decodable>(
        with request: URLRequest, decoder: JSONDecoder
    ) async throws -> T {
        let result = try await fetch(request)
        let data = result.data
        return try decoder.decode(T.self, from: data)
    }

Or something similar, it offers more control to the caller.

danielsaidi commented 1 week ago

Hi @jmg-duarte

I'm not sure if you're using this anymore, but if you do, I will release a 0.9.1 in which you can pass in a custom decoder.

jmg-duarte commented 1 week ago

Hey @danielsaidi, my venture using this stopped for unrelated reasons. I'll be taking it for a spin in future apps though