Skip to content

Commit

Permalink
Destroy res when keepAlive is false
Browse files Browse the repository at this point in the history
  • Loading branch information
AndrewBarba committed Feb 20, 2024
1 parent 03ca30f commit 0e26bdb
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ export async function fetch(input: RequestInfo, init?: RequestInit): Promise<Res
timeout: init?.timeout
})

// Define unified buffer handler
const responseBuffer = async () => {
const buf = await res.buffer()
if (init?.keepAlive === false) {
res.destroy()
}
return buf
}

// Build response
return {
headers: res.headers,
Expand All @@ -54,19 +63,17 @@ export async function fetch(input: RequestInfo, init?: RequestInit): Promise<Res
body: res.body,
close: res.close,
destroy: res.destroy,
async buffer() {
return res.buffer()
},
buffer: responseBuffer,
async arrayBuffer() {
const buffer = await res.buffer()
const buffer = await responseBuffer()
return Uint8Array.from(buffer)
},
async text() {
const buffer = await res.buffer()
const buffer = await responseBuffer()
return buffer.toString('utf8')
},
async json() {
const buffer = await res.buffer()
const buffer = await responseBuffer()
const text = buffer.toString('utf8')
return JSON.parse(text)
}
Expand Down
14 changes: 14 additions & 0 deletions test/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,20 @@ describe('fetch', () => {
assert.isTrue(res.body.destroyed)
})

it('should fetch without keepAlive', async () => {
const res = await fetch('https://httpbin.org/json', { keepAlive: false })
await res.json()
assert.isTrue(res.body.closed)
assert.isTrue(res.body.destroyed)
})

it('should fetch with keepAlive', async () => {
const res = await fetch('https://httpbin.org/json', { keepAlive: true })
await res.json()
assert.isFalse(res.body.closed)
assert.isFalse(res.body.destroyed)
})

it('should fetch concurrently', async () => {
const url = 'https://whoami.app.swift.cloud'
const promises: any[] = []
Expand Down

0 comments on commit 0e26bdb

Please sign in to comment.