metatext/Shared/Networking/HTTPClient.swift

58 lines
1.7 KiB
Swift
Raw Normal View History

// Copyright © 2020 Metabolist. All rights reserved.
import Foundation
import Combine
import Alamofire
2020-08-12 07:24:39 +00:00
typealias Session = Alamofire.Session
class HTTPClient {
private let session: Session
private let decoder: DataDecoder
2020-08-12 07:24:39 +00:00
init(session: Session, decoder: DataDecoder = JSONDecoder()) {
self.session = session
self.decoder = decoder
}
func request<T: DecodableTarget>(_ target: T) -> AnyPublisher<T.ResultType, Error> {
requestPublisher(target).value().mapError { $0 as Error }.eraseToAnyPublisher()
}
func request<T: DecodableTarget, E: Error & Decodable>(
_ target: T,
decodeErrorsAs errorType: E.Type) -> AnyPublisher<T.ResultType, Error> {
let decoder = self.decoder
return requestPublisher(target)
.tryMap { response -> T.ResultType in
switch response.result {
case let .success(decoded): return decoded
case let .failure(error):
if
let data = response.data,
let decodedError = try? decoder.decode(E.self, from: data) {
throw decodedError
}
throw error
}
}
.eraseToAnyPublisher()
}
}
private extension HTTPClient {
private func requestPublisher<T: DecodableTarget>(_ target: T) -> DataResponsePublisher<T.ResultType> {
#if DEBUG
if let url = try? target.asURLRequest().url {
StubbingURLProtocol.setTarget(target, forURL: url)
}
#endif
return session.request(target)
.validate()
.publishDecodable(type: T.ResultType.self, decoder: decoder)
}
}