Skip to content

Commit 763f479

Browse files
authored
Merge pull request #4 from zunda-pixel/fix-HTTPClient
Fix http client
2 parents 0f78ffb + 1c91759 commit 763f479

File tree

3 files changed

+19
-14
lines changed

3 files changed

+19
-14
lines changed

Package.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ let package = Package(
99
.library(name: "D1Kit", targets: ["D1Kit"]),
1010
],
1111
dependencies: [
12-
.package(url: "https://github.com/apple/swift-http-types.git", from: "1.0.0"),
12+
.package(url: "https://github.com/apple/swift-http-types.git", from: "1.3.0"),
1313
],
1414
targets: [
1515
.target(

Sources/D1KitFoundation/URLSession+Linux.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import Foundation
22
#if canImport(FoundationNetworking)
33
import FoundationNetworking
4+
#endif
45

6+
#if compiler(<6)
57
extension URLSession {
68
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
79
return try await withCheckedThrowingContinuation { continuation in
@@ -15,5 +17,17 @@ extension URLSession {
1517
task.resume()
1618
}
1719
}
20+
func upload(for request: URLRequest, from data: Data?) async throws -> (Data, URLResponse) {
21+
return try await withCheckedThrowingContinuation { continuation in
22+
let task = self.uploadTask(with: request, from: data) { (data, response, error) in
23+
guard let data = data, let response = response else {
24+
let error = error ?? URLError(.badServerResponse)
25+
return continuation.resume(throwing: error)
26+
}
27+
continuation.resume(returning: (data, response))
28+
}
29+
task.resume()
30+
}
31+
}
1832
}
1933
#endif

Sources/D1KitFoundation/URLSessionHTTPClient.swift

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,13 @@ import FoundationNetworking
66
import HTTPTypes
77
import HTTPTypesFoundation
88

9-
private enum HTTPTypeConversionError: Error {
10-
case failedToConvertHTTPRequestToURLRequest
11-
case failedToConvertURLResponseToHTTPResponse
12-
}
13-
149
extension URLSession: HTTPClientProtocol {
1510
public func execute(_ request: HTTPRequest, body: Data?) async throws -> (Data, HTTPResponse) {
16-
guard var urlRequest = URLRequest(httpRequest: request) else {
17-
throw HTTPTypeConversionError.failedToConvertHTTPRequestToURLRequest
18-
}
19-
urlRequest.httpBody = body
20-
let (data, urlResponse) = try await self.data(for: urlRequest)
21-
guard let response = (urlResponse as? HTTPURLResponse)?.httpResponse else {
22-
throw HTTPTypeConversionError.failedToConvertURLResponseToHTTPResponse
11+
if let body {
12+
try await self.upload(for: request, from: body)
13+
} else {
14+
try await self.data(for: request)
2315
}
24-
return (data, response)
2516
}
2617
}
2718

0 commit comments

Comments
 (0)