Skip to content

Commit 0631069

Browse files
authored
fix(functions): fix streamed responses (#525)
1 parent 7601e17 commit 0631069

File tree

1 file changed

+20
-18
lines changed

1 file changed

+20
-18
lines changed

Sources/Functions/FunctionsClient.swift

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -198,24 +198,7 @@ public final class FunctionsClient: Sendable {
198198

199199
let urlRequest = buildRequest(functionName: functionName, options: invokeOptions).urlRequest
200200

201-
let task = session.dataTask(with: urlRequest) { data, response, _ in
202-
guard let httpResponse = response as? HTTPURLResponse else {
203-
continuation.finish(throwing: URLError(.badServerResponse))
204-
return
205-
}
206-
207-
guard 200 ..< 300 ~= httpResponse.statusCode else {
208-
let error = FunctionsError.httpError(code: httpResponse.statusCode, data: data ?? Data())
209-
continuation.finish(throwing: error)
210-
return
211-
}
212-
213-
let isRelayError = httpResponse.value(forHTTPHeaderField: "x-relay-error") == "true"
214-
if isRelayError {
215-
continuation.finish(throwing: FunctionsError.relayError)
216-
}
217-
}
218-
201+
let task = session.dataTask(with: urlRequest)
219202
task.resume()
220203

221204
continuation.onTermination = { _ in
@@ -259,4 +242,23 @@ final class StreamResponseDelegate: NSObject, URLSessionDataDelegate, Sendable {
259242
func urlSession(_: URLSession, task _: URLSessionTask, didCompleteWithError error: (any Error)?) {
260243
continuation.finish(throwing: error)
261244
}
245+
246+
func urlSession(_: URLSession, dataTask _: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
247+
guard let httpResponse = response as? HTTPURLResponse else {
248+
continuation.finish(throwing: URLError(.badServerResponse))
249+
return
250+
}
251+
252+
guard 200 ..< 300 ~= httpResponse.statusCode else {
253+
let error = FunctionsError.httpError(code: httpResponse.statusCode, data: Data())
254+
continuation.finish(throwing: error)
255+
return
256+
}
257+
258+
let isRelayError = httpResponse.value(forHTTPHeaderField: "x-relay-error") == "true"
259+
if isRelayError {
260+
continuation.finish(throwing: FunctionsError.relayError)
261+
}
262+
completionHandler(.allow)
263+
}
262264
}

0 commit comments

Comments
 (0)