From feb5006e36df06943ab1d76d80d8de29e6a9a1df Mon Sep 17 00:00:00 2001 From: uzlopak Date: Sat, 14 Sep 2024 03:07:19 +0200 Subject: [PATCH] fetch: optimize .bytes() mixin --- lib/web/fetch/body.js | 6 +++--- test/fetch/client-fetch.js | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/lib/web/fetch/body.js b/lib/web/fetch/body.js index 683a67400c8..e8478ea3f5c 100644 --- a/lib/web/fetch/body.js +++ b/lib/web/fetch/body.js @@ -305,6 +305,8 @@ function throwIfAborted (state) { } function bodyMixinMethods (instance) { + const uint8ArrayFromBytes = Uint8Array.from.bind(Uint8Array) + const methods = { blob () { // The blob() method steps are to return the result of @@ -405,9 +407,7 @@ function bodyMixinMethods (instance) { // The bytes() method steps are to return the result of running consume body // with this and the following step given a byte sequence bytes: return the // result of creating a Uint8Array from bytes in this’s relevant realm. - return consumeBody(this, (bytes) => { - return new Uint8Array(bytes) - }, instance) + return consumeBody(this, uint8ArrayFromBytes, instance) } } diff --git a/test/fetch/client-fetch.js b/test/fetch/client-fetch.js index 3003021390b..b1e98374d43 100644 --- a/test/fetch/client-fetch.js +++ b/test/fetch/client-fetch.js @@ -84,6 +84,21 @@ test('request arrayBuffer', (t, done) => { }) }) +test('request bytes', (t, done) => { + const { deepStrictEqual } = tspl(t, { plan: 1 }) + + const server = createServer((req, res) => { + res.end('hello world') + }) + t.after(closeServerAsPromise(server)) + + server.listen(0, async () => { + const body = await fetch(`http://localhost:${server.address().port}`) + deepStrictEqual(new Uint8Array(Buffer.from('hello world')), await body.bytes()) + done() + }) +}) + test('should set type of blob object to the value of the `Content-Type` header from response', (t, done) => { const { strictEqual } = tspl(t, { plan: 1 })