-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: improve repsonse body normalization
- Loading branch information
1 parent
443a947
commit 86b1ae8
Showing
3 changed files
with
31 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
const decoder = new TextDecoder(); | ||
export default function consumeResponseBody( | ||
res: Response | ||
): AsyncIterator<string, void> | undefined { | ||
if (res.body) { | ||
if ((res.body as any).getReader) { | ||
return consumeBodyReader(res.body.getReader()); | ||
} | ||
|
||
if ((res.body as any)[Symbol.asyncIterator]) { | ||
return (res.body as any)[Symbol.asyncIterator](); | ||
} | ||
} | ||
|
||
throw new Error("Response body must be a stream."); | ||
} | ||
|
||
async function* consumeBodyReader( | ||
reader: ReadableStreamDefaultReader<Uint8Array> | ||
) { | ||
do { | ||
const next = await reader.read(); | ||
if (next.done) break; | ||
yield decoder.decode(next.value); | ||
} while (true); | ||
} |