Skip to content
Open
Show file tree
Hide file tree
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
11 changes: 3 additions & 8 deletions src/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,21 +46,16 @@ export class Response {
constructor(body?: BodyInit | null, init?: ResponseInit) {
let headers: HeadersInit | undefined
this.#body = body
if (init instanceof Response) {
if (init instanceof GlobalResponse) {
const cachedGlobalResponse = (init as any)[responseCache]
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse
// instantiate GlobalResponse cache and this object always returns value from global.Response
this[getResponseCache]()
return
} else {
this.#init = init.#init
// Read headers via the live getter so mutations made on `init` after
// construction (e.g. `init.headers.append('Set-Cookie', ...)`) are
// preserved on the clone. `new Headers(...)` still produces an
// independent copy so parent and child do not share the same object.
headers = new Headers(init.headers)
}
this.#init = init instanceof Response ? init.#init : init
headers = new Headers(init.headers)
} else {
this.#init = init
}
Expand Down
10 changes: 10 additions & 0 deletions test/response.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,16 @@ describe('Response', () => {
expect(res.headers.get('location')).toEqual('https://example.com/')
})

it('Should copy headers when rebuilding a response from fetch()', async () => {
const upstream = await fetch(`http://localhost:${port}`)
const rebuilt = new Response(upstream.body, upstream)
rebuilt.headers.set('x-test', '1')
expect(rebuilt.headers.get('x-test')).toEqual('1')
expect(rebuilt.headers.get('content-type')).toEqual('application/json charset=UTF-8')
expect(upstream.headers.get('x-test')).toBeNull()
expect(await rebuilt.json()).toEqual({ status: 'ok' })
})

it('Nested constructors should not cause an error even if ReadableStream is specified', async () => {
const stream = new Response('hono').body
const parentResponse = new Response(stream)
Expand Down