Skip to content

Commit

Permalink
fix: set correct "Content-Length" response header for special charact…
Browse files Browse the repository at this point in the history
…ers (#2045) (#2046)
  • Loading branch information
ZeroCho authored Feb 27, 2024
1 parent 23fc364 commit eb3e284
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
26 changes: 26 additions & 0 deletions src/core/HttpResponse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ describe('HttpResponse.text()', () => {
})
})

it('creates a text response with special characters', async () => {
const response = HttpResponse.text('안녕 세상', { status: 201 })

expect(response.status).toBe(201)
expect(response.statusText).toBe('Created')
expect(response.body).toBeInstanceOf(ReadableStream)
expect(await response.text()).toBe('안녕 세상')
expect(Object.fromEntries(response.headers.entries())).toEqual({
'content-length': '13',
'content-type': 'text/plain',
})
})

it('allows overriding the "Content-Type" response header', async () => {
const response = HttpResponse.text('hello world', {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
Expand Down Expand Up @@ -68,6 +81,19 @@ describe('HttpResponse.json()', () => {
})
})

it('creates a json response given an object with special characters', async () => {
const response = HttpResponse.json({ firstName: '제로' })

expect(response.status).toBe(200)
expect(response.statusText).toBe('OK')
expect(response.body).toBeInstanceOf(ReadableStream)
expect(await response.json()).toEqual({ firstName: '제로' })
expect(Object.fromEntries(response.headers.entries())).toEqual({
'content-length': '22',
'content-type': 'application/json',
})
})

it('creates a json response given an array', async () => {
const response = HttpResponse.json([1, 2, 3])

Expand Down
4 changes: 2 additions & 2 deletions src/core/HttpResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export class HttpResponse extends Response {
if (!responseInit.headers.has('Content-Length')) {
responseInit.headers.set(
'Content-Length',
body ? body.length.toString() : '0',
body ? new Blob([body]).size.toString() : '0',
)
}

Expand Down Expand Up @@ -95,7 +95,7 @@ export class HttpResponse extends Response {
if (!responseInit.headers.has('Content-Length')) {
responseInit.headers.set(
'Content-Length',
responseText ? responseText.length.toString() : '0',
responseText ? new Blob([responseText]).size.toString() : '0',
)
}

Expand Down

0 comments on commit eb3e284

Please sign in to comment.