Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Improve Body's bufferFromStream #5826

Merged
merged 1 commit into from
May 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 21 additions & 28 deletions cli/js/web/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,36 +58,29 @@ function concatenate(...arrays: Uint8Array[]): ArrayBuffer {
return result.buffer as ArrayBuffer;
}

function bufferFromStream(stream: ReadableStreamReader): Promise<ArrayBuffer> {
return new Promise((resolve, reject): void => {
const parts: Uint8Array[] = [];
const encoder = new TextEncoder();
// recurse
(function pump(): void {
stream
.read()
.then(({ done, value }): void => {
if (done) {
return resolve(concatenate(...parts));
}
async function bufferFromStream(
stream: ReadableStreamReader
): Promise<ArrayBuffer> {
const parts: Uint8Array[] = [];
const encoder = new TextEncoder();

if (typeof value === "string") {
parts.push(encoder.encode(value));
} else if (value instanceof ArrayBuffer) {
parts.push(new Uint8Array(value));
} else if (!value) {
// noop for undefined
} else {
reject("unhandled type on stream read");
}
while (true) {
const { done, value } = await stream.read();

if (done) break;

if (typeof value === "string") {
parts.push(encoder.encode(value));
} else if (value instanceof ArrayBuffer) {
parts.push(new Uint8Array(value));
} else if (!value) {
// noop for undefined
} else {
throw new Error("unhandled type on stream read");
}
}

return pump();
})
.catch((err): void => {
reject(err);
});
})();
});
return concatenate(...parts);
}

function getHeaderValueParams(value: string): Map<string, string> {
Expand Down