Skip to content

Commit

Permalink
refactor(streaming): make response body streaming polyfill more spec-…
Browse files Browse the repository at this point in the history
…compliant (#44)
  • Loading branch information
stainless-bot authored and RobertCraigie committed Jul 11, 2023
1 parent 5cfb96f commit 047d328
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
2 changes: 1 addition & 1 deletion .release-please-manifest.json
@@ -1,3 +1,3 @@
{
".": "0.5.2"
".": "0.5.3"
}
16 changes: 12 additions & 4 deletions src/streaming.ts
Expand Up @@ -259,19 +259,27 @@ function partition(str: string, delimiter: string): [string, string, string] {
* Most browsers don't yet have async iterable support for ReadableStream,
* and Node has a very different way of reading bytes from its "ReadableStream".
*
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1624185965
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
*/
function readableStreamAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {
if (stream[Symbol.asyncIterator]) return stream;

const reader = stream.getReader();
return {
next() {
return reader.read();
async next() {
try {
const result = await reader.read();
if (result?.done) reader.releaseLock(); // release lock when stream becomes closed
return result;
} catch (e) {
reader.releaseLock(); // release lock when stream becomes errored
throw e;
}
},
async return() {
reader.cancel();
const cancelPromise = reader.cancel();
reader.releaseLock();
await cancelPromise;
return { done: true, value: undefined };
},
[Symbol.asyncIterator]() {
Expand Down

0 comments on commit 047d328

Please sign in to comment.