Skip to content

Commit 8f08006

Browse files
author
Ihor Makhnyk
committed
Move json processing to separate method
1 parent 80e9160 commit 8f08006

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

Sources/OpenAI/Private/StreamingSession.swift

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
2828
return session
2929
}()
3030

31-
private var prevChunkBuffer = ""
31+
private var previousChunkBuffer = ""
3232

3333
init(urlRequest: URLRequest) {
3434
self.urlRequest = urlRequest
@@ -49,11 +49,20 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
4949
onProcessingError?(self, StreamingError.unknownContent)
5050
return
5151
}
52-
let jsonObjects = "\(prevChunkBuffer)\(stringContent)"
52+
processJSON(from: stringContent)
53+
}
54+
55+
}
56+
57+
extension StreamingSession {
58+
59+
private func processJSON(from stringContent: String) {
60+
let jsonObjects = "\(previousChunkBuffer)\(stringContent)"
5361
.components(separatedBy: "data:")
5462
.filter { $0.isEmpty == false }
5563
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
56-
prevChunkBuffer = ""
64+
65+
previousChunkBuffer = ""
5766

5867
guard jsonObjects.isEmpty == false, jsonObjects.first != streamingCompletionMarker else {
5968
return
@@ -82,13 +91,13 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
8291
onProcessingError?(self, decoded)
8392
} catch {
8493
if index == jsonObjects.count - 1 {
85-
// Chunk ends in a partial JSON
86-
prevChunkBuffer = "data: \(jsonContent)"
94+
previousChunkBuffer = "data: \(jsonContent)" // Chunk ends in a partial JSON
8795
} else {
8896
onProcessingError?(self, apiError)
8997
}
9098
}
9199
}
92100
}
93101
}
102+
94103
}

0 commit comments

Comments
 (0)