diff --git a/Sources/TinyNetworking/Endpoint.swift b/Sources/TinyNetworking/Endpoint.swift index b26e905..3081cb4 100644 --- a/Sources/TinyNetworking/Endpoint.swift +++ b/Sources/TinyNetworking/Endpoint.swift @@ -240,3 +240,31 @@ extension URLSession { } } +#if canImport(Combine) +import Combine + +@available(iOS 13, macOS 10.15, watchOS 6, tvOS 13, *) +extension URLSession { + /// Returns a publisher that wraps a URL session data task for a given Endpoint. + /// + /// - Parameters: + /// - e: The endpoint. + /// - Returns: The publisher of a dataTask. + public func load(_ e: Endpoint) -> AnyPublisher { + let r = e.request + return dataTaskPublisher(for: r) + .tryMap { data, resp in + guard let h = resp as? HTTPURLResponse else { + throw UnknownError() + } + + guard e.expectedStatusCode(h.statusCode) else { + throw WrongStatusCodeError(statusCode: h.statusCode, response: h) + } + + return try e.parse(data, resp).get() + } + .eraseToAnyPublisher() + } +} +#endif