Skip to content

Commit

Permalink
Merge pull request #4 from zunda-pixel/fix-HTTPClient
Browse files Browse the repository at this point in the history
Fix http client
  • Loading branch information
sidepelican authored Aug 8, 2024
2 parents 0f78ffb + 1c91759 commit 763f479
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 14 deletions.
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ let package = Package(
.library(name: "D1Kit", targets: ["D1Kit"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-http-types.git", from: "1.0.0"),
.package(url: "https://github.com/apple/swift-http-types.git", from: "1.3.0"),
],
targets: [
.target(
Expand Down
14 changes: 14 additions & 0 deletions Sources/D1KitFoundation/URLSession+Linux.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

#if compiler(<6)
extension URLSession {
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
return try await withCheckedThrowingContinuation { continuation in
Expand All @@ -15,5 +17,17 @@ extension URLSession {
task.resume()
}
}
func upload(for request: URLRequest, from data: Data?) async throws -> (Data, URLResponse) {
return try await withCheckedThrowingContinuation { continuation in
let task = self.uploadTask(with: request, from: data) { (data, response, error) in
guard let data = data, let response = response else {
let error = error ?? URLError(.badServerResponse)
return continuation.resume(throwing: error)
}
continuation.resume(returning: (data, response))
}
task.resume()
}
}
}
#endif
17 changes: 4 additions & 13 deletions Sources/D1KitFoundation/URLSessionHTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,13 @@ import FoundationNetworking
import HTTPTypes
import HTTPTypesFoundation

private enum HTTPTypeConversionError: Error {
case failedToConvertHTTPRequestToURLRequest
case failedToConvertURLResponseToHTTPResponse
}

extension URLSession: HTTPClientProtocol {
public func execute(_ request: HTTPRequest, body: Data?) async throws -> (Data, HTTPResponse) {
guard var urlRequest = URLRequest(httpRequest: request) else {
throw HTTPTypeConversionError.failedToConvertHTTPRequestToURLRequest
}
urlRequest.httpBody = body
let (data, urlResponse) = try await self.data(for: urlRequest)
guard let response = (urlResponse as? HTTPURLResponse)?.httpResponse else {
throw HTTPTypeConversionError.failedToConvertURLResponseToHTTPResponse
if let body {
try await self.upload(for: request, from: body)
} else {
try await self.data(for: request)
}
return (data, response)
}
}

Expand Down

0 comments on commit 763f479

Please sign in to comment.