Created
December 19, 2023 14:26
-
-
Save yannisalexiou/ffcb7bf4226e407b8788882e4cc430e9 to your computer and use it in GitHub Desktop.
Simple JSON decoding using protocol and default implementation. With this you can separate the decodable logic from repository and api client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum DecodeError: Swift.Error { | |
case connectivity | |
case invalidData | |
} | |
protocol JSONDecodable { | |
static func jsonDecode<D: Decodable>( | |
_ data: Data, | |
from response: HTTPURLResponse | |
) throws -> D | |
} | |
extension JSONDecodable { | |
static func jsonDecode<D: Decodable>( | |
_ data: Data, | |
from response: HTTPURLResponse | |
) throws -> D { | |
guard response.isOK, | |
let root = try? JSONDecoder().decode(D.self, from: data) | |
else { | |
throw DecodeError.invalidData | |
} | |
return root | |
} | |
} | |
protocol JSONMapper: JSONDecodable { | |
typealias GetResult<T> = Swift.Result<T, Error> | |
static func map<T: Decodable>( | |
_ data: Data, | |
from response: HTTPURLResponse | |
) -> GetResult<T> | |
} | |
extension JSONMapper { | |
static func map<T: Decodable>( | |
_ data: Data, | |
from response: HTTPURLResponse | |
) -> GetResult<T> { | |
do { | |
let items: T = try Self.jsonDecode(data, from: response) | |
return .success(items) | |
} catch { | |
return .failure(error) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment