From ddda669a02fa394627dda2ac3d7ea0ed8830b920 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Tue, 22 Dec 2020 14:14:23 +0100 Subject: [PATCH] fix: implement ReadableStream fetch body handling (#8855) --- cli/tests/unit/fetch_test.ts | 40 ++++++++++++++++++++++++++++++++++++ op_crates/fetch/26_fetch.js | 8 ++++++-- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/cli/tests/unit/fetch_test.ts b/cli/tests/unit/fetch_test.ts index 6f90a1847c..359a24e952 100644 --- a/cli/tests/unit/fetch_test.ts +++ b/cli/tests/unit/fetch_test.ts @@ -1013,3 +1013,43 @@ MNf4EgWfK+tZMnuqfpfO9740KzfcVoMNo4QJD4yn5YxroUOO/Azi client.close(); }, ); + +unitTest( + { + perms: { net: true }, + }, + async function fetchPostBodyReadableStream(): Promise { + const addr = "127.0.0.1:4502"; + const buf = bufferServer(addr); + const stream = new TransformStream(); + const writer = stream.writable.getWriter(); + await writer.write(new TextEncoder().encode("hello ")); + await writer.write(new TextEncoder().encode("world")); + await writer.close(); + const response = await fetch(`http://${addr}/blah`, { + method: "POST", + headers: [ + ["Hello", "World"], + ["Foo", "Bar"], + ], + body: stream.readable, + }); + await response.arrayBuffer(); + assertEquals(response.status, 404); + assertEquals(response.headers.get("Content-Length"), "2"); + + const actual = new TextDecoder().decode(buf.bytes()); + const expected = [ + "POST /blah HTTP/1.1\r\n", + "hello: World\r\n", + "foo: Bar\r\n", + "accept: */*\r\n", + `user-agent: Deno/${Deno.version.deno}\r\n`, + "accept-encoding: gzip, br\r\n", + `host: ${addr}\r\n`, + `content-length: 11\r\n\r\n`, + "hello world", + ].join(""); + assertEquals(actual, expected); + }, +); diff --git a/op_crates/fetch/26_fetch.js b/op_crates/fetch/26_fetch.js index 95ee968124..0835e12a15 100644 --- a/op_crates/fetch/26_fetch.js +++ b/op_crates/fetch/26_fetch.js @@ -1246,8 +1246,12 @@ body = multipartBuilder.getBody(); contentType = multipartBuilder.getContentType(); } else { - // TODO: ReadableStream - throw new Error("Not implemented"); + // TODO(lucacasonato): do this in a streaming fashion once we support it + const buf = new Buffer(); + for await (const chunk of init.body) { + buf.write(chunk); + } + body = buf.bytes(); } if (contentType && !headers.has("content-type")) { headers.set("content-type", contentType);