Skip to content

Commit

Permalink
fetch: optimize .bytes() mixin
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak committed Sep 14, 2024
1 parent c773728 commit feb5006
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/web/fetch/body.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}

Expand Down
15 changes: 15 additions & 0 deletions test/fetch/client-fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 })

Expand Down

0 comments on commit feb5006

Please sign in to comment.