streamJsonData method
POST a JSON body and expose the (chunked) response body as a byte stream.
Implementation
Stream<Uint8List> streamJsonData(String path, Map<String, dynamic> body, {Map<String, dynamic>? headers}) async* {
// Clean up the relative path without mutating the parameter (parameters are
// final in Dart).
final relative = path.startsWith('/') ? path.substring(1) : path;
final url = baseUrl.resolve(relative);
// Build a streamed HTTP request.
final req = Request('POST', url)
..headers.addAll(getHeaders({'Content-Type': 'application/json', if (headers != null) ...headers}) ?? {})
..body = jsonEncode(body);
final res = await httpClient.send(req);
// Fail fast on non-2xx.
if (res.statusCode < 200 || res.statusCode >= 300) {
throw OpenAIRequestException(
statusCode: res.statusCode,
message: res.reasonPhrase ?? "request failed",
);
}
// Pipe the server’s chunked body to the caller.
await for (final chunk in res.stream) {
yield Uint8List.fromList(chunk);
}
}