|
1 | 1 | import Foundation
|
| 2 | +import Get |
2 | 3 |
|
3 | 4 | public final class FunctionsClient {
|
4 | 5 | let url: URL
|
5 | 6 | var headers: [String: String]
|
6 |
| - let http: FunctionsHTTPClient |
| 7 | + |
| 8 | + let client: APIClient |
7 | 9 |
|
8 | 10 | public init(
|
9 | 11 | url: URL,
|
10 | 12 | headers: [String: String] = [:],
|
11 |
| - http: FunctionsHTTPClient? = nil |
| 13 | + apiClientDelegate: APIClientDelegate? = nil |
12 | 14 | ) {
|
13 | 15 | self.url = url
|
14 | 16 | self.headers = headers
|
15 |
| - self.http = http ?? DefaultFunctionsHTTPClient() |
16 |
| - |
17 | 17 | self.headers["X-Client-Info"] = "functions-swift/\(version)"
|
| 18 | + client = APIClient(baseURL: url) { |
| 19 | + $0.delegate = apiClientDelegate |
| 20 | + } |
18 | 21 | }
|
19 | 22 |
|
20 | 23 | /// Updates the authorization header.
|
@@ -71,24 +74,28 @@ public final class FunctionsClient {
|
71 | 74 | functionName: String,
|
72 | 75 | invokeOptions: FunctionInvokeOptions
|
73 | 76 | ) async throws -> (Data, HTTPURLResponse) {
|
74 |
| - let body = invokeOptions.body |
75 |
| - let invokeHeaders = invokeOptions.headers |
| 77 | + let request = Request( |
| 78 | + path: functionName, |
| 79 | + method: .post, |
| 80 | + body: invokeOptions.body, |
| 81 | + headers: invokeOptions.headers.merging(headers) { first, _ in first } |
| 82 | + ) |
| 83 | + |
| 84 | + let response = try await client.data(for: request) |
76 | 85 |
|
77 |
| - var request = URLRequest(url: url.appendingPathComponent(functionName)) |
78 |
| - request.httpMethod = "POST" |
79 |
| - request.httpBody = body |
80 |
| - request.allHTTPHeaderFields = invokeHeaders.merging(headers) { invokeHeader, _ in invokeHeader } |
| 86 | + guard let httpResponse = response.response as? HTTPURLResponse else { |
| 87 | + throw URLError(.badServerResponse) |
| 88 | + } |
81 | 89 |
|
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) |
| 90 | + guard 200 ..< 300 ~= httpResponse.statusCode else { |
| 91 | + throw FunctionsError.httpError(code: httpResponse.statusCode, data: response.data) |
85 | 92 | }
|
86 | 93 |
|
87 |
| - let isRelayError = response.value(forHTTPHeaderField: "x-relay-error") == "true" |
| 94 | + let isRelayError = httpResponse.value(forHTTPHeaderField: "x-relay-error") == "true" |
88 | 95 | if isRelayError {
|
89 | 96 | throw FunctionsError.relayError
|
90 | 97 | }
|
91 | 98 |
|
92 |
| - return (data, response) |
| 99 | + return (response.data, httpResponse) |
93 | 100 | }
|
94 | 101 | }
|
0 commit comments