Skip to content

Commit 7eacf54

Browse files
committed
🐛 Fix iterableStream - resolve the generator even the stream turns out to be empty
1 parent 90859b4 commit 7eacf54

File tree

1 file changed

+12
-3
lines changed
  • packages/@ackee/antonio-core/src/modules/response/iterableStream

1 file changed

+12
-3
lines changed

packages/@ackee/antonio-core/src/modules/response/iterableStream/index.ts

+12-3
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,33 @@ export async function* iterableStream(stream: Body['body'], contentTypeIsJson: b
66
}
77

88
const reader = stream.getReader();
9-
const decoder = new TextDecoder();
10-
const parser = contentTypeIsJson ? new ChunkToJsonParser() : null;
119

1210
try {
11+
const decoder = new TextDecoder();
12+
const parser = contentTypeIsJson ? new ChunkToJsonParser() : null;
1313
let result = await reader.read();
14+
let yieldedSome = false;
15+
let parsedChunk: string | any[] | undefined;
1416

1517
while (!result.done) {
1618
const arrayBuffer = result.value;
1719
const decodedChunk = decoder.decode(arrayBuffer, { stream: true });
1820

19-
const parsedChunk = parser ? parser.parse(decodedChunk) : decodedChunk;
21+
parsedChunk = parser ? parser.parse(decodedChunk) : decodedChunk;
2022

2123
if (parsedChunk.length > 0) {
2224
yield parsedChunk;
25+
yieldedSome = true;
2326
}
2427

2528
result = await reader.read();
2629
}
30+
31+
// If every chunk was empty, yield now, at the end, the empty chunk as the last value.
32+
// Otherwise the generator wouldn't ever end.
33+
if (!yieldedSome) {
34+
yield parsedChunk;
35+
}
2736
} catch (e) {
2837
reader.releaseLock();
2938
await stream.cancel();

0 commit comments

Comments
 (0)