Skip to content

Commit 6903ab2

Browse files
committed
instantiate json encoder and decoder once
1 parent 265424e commit 6903ab2

File tree

2 files changed

+13
-12
lines changed

2 files changed

+13
-12
lines changed

Sources/OpenAI/Client.swift

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,20 @@ public final class Client {
99

1010
internal(set) public var session: URLSession
1111

12+
private let encoder: JSONEncoder
13+
private let decoder: JSONDecoder
14+
1215
public init(session: URLSession = URLSession(configuration: .default), host: URL? = nil, apiKey: String) {
1316
self.session = session
1417
self.host = host ?? Self.defaultHost
1518
self.apiKey = apiKey
19+
self.encoder = JSONEncoder()
20+
self.decoder = JSONDecoder()
21+
self.decoder.dateDecodingStrategy = .custom { decoder in
22+
let container = try decoder.singleValueContainer()
23+
let dateInt = try container.decode(Int.self)
24+
return Date(timeIntervalSince1970: TimeInterval(dateInt))
25+
}
1626
}
1727

1828
public enum Error: Swift.Error, CustomStringConvertible {
@@ -185,7 +195,7 @@ extension Client {
185195
req.httpBody = try encodeMultipartFormData(body, boundary: boundary)
186196
} else {
187197
req.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
188-
req.httpBody = try JSONEncoder().encode(body)
198+
req.httpBody = try encoder.encode(body)
189199
}
190200
}
191201
return req
@@ -218,14 +228,4 @@ extension Client {
218228
data.append("--\(boundary)--\r\n".data(using: .utf8)!)
219229
return data
220230
}
221-
222-
private var decoder: JSONDecoder {
223-
let decoder = JSONDecoder()
224-
decoder.dateDecodingStrategy = .custom { decoder in
225-
let container = try decoder.singleValueContainer()
226-
let dateInt = try container.decode(Int.self)
227-
return Date(timeIntervalSince1970: TimeInterval(dateInt))
228-
}
229-
return decoder
230-
}
231231
}

Sources/OpenAI/StreamingSession.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,15 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
1616

1717
private let session: URLSession
1818
private let request: URLRequest
19+
private let decoder: JSONDecoder
1920

2021
private var streamingBuffer = ""
2122
private let streamingCompletionMarker = "[DONE]"
2223

2324
init(session: URLSession, request: URLRequest) {
2425
self.session = session
2526
self.request = request
27+
self.decoder = JSONDecoder()
2628
}
2729

2830
func perform() {
@@ -58,7 +60,6 @@ final class StreamingSession<ResultType: Codable>: NSObject, Identifiable, URLSe
5860
onProcessingError?(self, StreamingError.unknownContent)
5961
return
6062
}
61-
let decoder = JSONDecoder()
6263
do {
6364
let object = try decoder.decode(ResultType.self, from: jsonData)
6465
onReceiveContent?(self, object)

0 commit comments

Comments
 (0)