Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proof of concept: Two types of decoders #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions Sources/URLSessionDecodable/DataDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,25 @@

import Foundation

public protocol DataDecoder {
public protocol AnyTypeDecoder {

/// Decodes an instance of the indicated type.
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T: Decodable

}

// For legacy reasons
public typealias DataDecoder = AnyTypeDecoder

public protocol ConcreteTypeDecoder {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure about the naming


associatedtype DecodedType

/// Decodes an instance of the indicated type.
func decode(_ data: Data) throws -> DecodedType

}

// MARK: -

extension JSONDecoder: DataDecoder {}
extension JSONDecoder: AnyTypeDecoder {}
58 changes: 49 additions & 9 deletions Sources/URLSessionDecodable/URLSessionDecodable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,58 @@ public enum HTTPMethod: String {
}

extension URLSession {

//swiftlint:disable function_parameter_count

/// Creates a task that retrieves the contents of the specified URL, decodes the response,
/// then calls a handler upon completion.
///
/// The response data will be decoded to `T` type when `statusCode` is in range `200..<300`
/// or `E` for other status codes.
/// The response data will be decoded to `T` type when `statusCode` is in range `200..<300`.
public func decodable<T, D: ConcreteTypeDecoder>(
with url: URL,
method: HTTPMethod,
parameters: ParametersEncoding?,
headers: HTTPHeaders?,
decoder: D,
completionHandler: @escaping (Result<T, URLSessionDecodableError>) -> Void
) -> URLSessionDataTask where D.DecodedType == T {
return createTask(
with: url,
method: method,
parameters: parameters,
headers: headers,
completionHandler: completionHandler
) { data -> T in
try decoder.decode(data)
}
}

public func decodable<T: Decodable>(
with url: URL,
method: HTTPMethod,
parameters: ParametersEncoding?,
headers: HTTPHeaders?,
decoder: DataDecoder,
decoder: AnyTypeDecoder,
completionHandler: @escaping (Result<T, URLSessionDecodableError>) -> Void
) -> URLSessionDataTask {
return createTask(
with: url,
method: method,
parameters: parameters,
headers: headers,
completionHandler: completionHandler
) { data -> T in
try decoder.decode(T.self, from: data)
}
}

private func createTask<T>(
with url: URL,
method: HTTPMethod,
parameters: ParametersEncoding?,
headers: HTTPHeaders?,
completionHandler: @escaping (Result<T, URLSessionDecodableError>) -> Void,
decoding: @escaping (Data) throws -> T
) -> URLSessionDataTask {
let request = self.request(with: url, method: method, parameters: parameters, headers: headers)
let task = dataTask(with: request) { data, response, error in
Expand All @@ -42,18 +81,19 @@ extension URLSession {
completionHandler(.failure(URLSessionDecodableError.nonHTTPResponse(response)))
return
}

completionHandler(Self.handle(response: httpResponse, data: data, decoder: decoder, url: url))
let result = Self.handle(response: httpResponse, data: data, url: url, decoding: decoding)
completionHandler(result)
}
return task
}

//swiftlint:enable function_parameter_count

private static func handle<T: Decodable>(
private static func handle<T>(
response: HTTPURLResponse,
data: Data,
decoder: DataDecoder,
url: URL
url: URL,
decoding: (Data) throws -> T
) -> Result<T, URLSessionDecodableError> {
guard 200..<300 ~= response.statusCode else {
let serverResponse = URLSessionDecodableError.ServerResponse(statusCode: response.statusCode,
Expand All @@ -63,7 +103,7 @@ extension URLSession {
}

do {
return try .success(decoder.decode(T.self, from: data))
return try .success(decoding(data))
} catch {
if #available(iOS 10.0, *) {
os_log("%@", "Error while decoding \(String(describing: type(of: T.self))) \(error)")
Expand Down