Skip to content

Commit bdaf7b3

Browse files
committed
Add FunctionsHTTPClient
1 parent 36c2754 commit bdaf7b3

File tree

2 files changed

+36
-12
lines changed

2 files changed

+36
-12
lines changed

Sources/Functions/FunctionsClient.swift

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,17 @@ import Foundation
33
public final class FunctionsClient {
44
let url: URL
55
var headers: [String: String]
6+
let http: FunctionsHTTPClient
67

7-
private let session: URLSession = .shared
8-
9-
public init(url: URL, headers: [String: String] = [:]) {
8+
public init(
9+
url: URL,
10+
headers: [String: String] = [:],
11+
http: FunctionsHTTPClient? = nil
12+
) {
1013
self.url = url
1114
self.headers = headers
15+
self.http = http ?? DefaultFunctionsHTTPClient()
16+
1217
self.headers["X-Client-Info"] = "functions-swift/\(version)"
1318
}
1419

@@ -74,20 +79,16 @@ public final class FunctionsClient {
7479
request.httpBody = body
7580
request.allHTTPHeaderFields = invokeHeaders.merging(headers) { invokeHeader, _ in invokeHeader }
7681

77-
let (data, response) = try await session.data(for: request)
78-
guard let httpResponse = response as? HTTPURLResponse else {
79-
throw URLError(.badServerResponse)
80-
}
81-
82-
guard 200 ..< 300 ~= httpResponse.statusCode else {
83-
throw FunctionsError.httpError(code: httpResponse.statusCode, data: data)
82+
let (data, response) = try await http.execute(request, client: self)
83+
guard 200 ..< 300 ~= response.statusCode else {
84+
throw FunctionsError.httpError(code: response.statusCode, data: data)
8485
}
8586

86-
let isRelayError = httpResponse.value(forHTTPHeaderField: "x-relay-error") == "true"
87+
let isRelayError = response.value(forHTTPHeaderField: "x-relay-error") == "true"
8788
if isRelayError {
8889
throw FunctionsError.relayError
8990
}
9091

91-
return (data, httpResponse)
92+
return (data, response)
9293
}
9394
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import Foundation
2+
3+
public protocol FunctionsHTTPClient {
4+
func execute(
5+
_ request: URLRequest,
6+
client: FunctionsClient
7+
) async throws -> (Data, HTTPURLResponse)
8+
}
9+
10+
public struct DefaultFunctionsHTTPClient: FunctionsHTTPClient {
11+
public init() {}
12+
13+
public func execute(
14+
_ request: URLRequest,
15+
client _: FunctionsClient
16+
) async throws -> (Data, HTTPURLResponse) {
17+
let (data, response) = try await URLSession.shared.data(for: request)
18+
guard let httpResponse = response as? HTTPURLResponse else {
19+
throw URLError(.badServerResponse)
20+
}
21+
return (data, httpResponse)
22+
}
23+
}

0 commit comments

Comments
 (0)