From abfe62b1c942ac55a65b05e24a9c0774e2835013 Mon Sep 17 00:00:00 2001 From: "Alkenso (Vladimir Vashurkin)" Date: Tue, 10 Dec 2024 07:30:33 +0200 Subject: [PATCH] Add HTTPClientProtocol to allow easier mocking --- Sources/SpellbookHTTP/HTTPClient.swift | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Sources/SpellbookHTTP/HTTPClient.swift b/Sources/SpellbookHTTP/HTTPClient.swift index 3f4ab4c..6fc9855 100644 --- a/Sources/SpellbookHTTP/HTTPClient.swift +++ b/Sources/SpellbookHTTP/HTTPClient.swift @@ -31,6 +31,21 @@ public protocol HTTPClientProtocol { func data(for request: () throws -> URLRequest, delegate: URLSessionTaskDelegate?) async throws -> HTTPResult } +@available(macOS 12.0, iOS 15, tvOS 15.0, watchOS 8.0, *) +extension HTTPClientProtocol { + public func data(for request: () throws -> URLRequest, completion: @escaping (Result, any Error>) -> Void) { + let request = Result(catching: request) + Task { + do { + let result = try await data(for: request.get, delegate: nil) + completion(.success(result)) + } catch { + completion(.failure(error)) + } + } + } +} + open class HTTPClient: HTTPClientProtocol { private var additionalHeaders = Synchronized>(.unfair, .init()) private let session: URLSession