Skip to content

Commit

Permalink
fix: generator set additional hooks header
Browse files Browse the repository at this point in the history
  • Loading branch information
bogeychan committed Jul 17, 2024
1 parent 3b3fbcd commit 4667e3c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
18 changes: 9 additions & 9 deletions src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,12 @@ const handleStream = (
) => {
let end = false

set ??= { headers: {} }

// Manually set transfer-encoding for direct response, eg. app.handle, eden
set.headers['transfer-encoding'] = 'chunked'
set.headers['content-type'] = 'text/event-stream; charset=utf-8'

return new Response(
new ReadableStream({
async start(controller) {
Expand Down Expand Up @@ -158,14 +164,7 @@ const handleStream = (
}
}
}),
{
...(set as ResponseInit),
headers: {
// Manually set transfer-encoding for direct response, eg. app.handle, eden
'transfer-encoding': 'chunked',
'content-type': 'text/event-stream; charset=utf-8'
}
}
set as ResponseInit
)
}

Expand Down Expand Up @@ -1055,7 +1054,8 @@ export const errorToResponse = (error: Error, set?: Context['set']) =>
cause: error?.cause
}),
{
status: set?.status !== 200 ? (set?.status as number) ?? 500 : 500,
status:
set?.status !== 200 ? ((set?.status as number) ?? 500) : 500,
headers: set?.headers
}
)
18 changes: 18 additions & 0 deletions test/response/stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,24 @@ describe('Stream', () => {
expect(response).toBe('abc')
})

it('handle stream with hook header', async () => {
const app = new Elysia()
.onRequest(({ set }) => {
set.headers['my'] = 'header'
})
.get('/', async function* () {
yield 'a'
})

const response = await app.handle(req('/'))

expect(response.headers.get('my')).toBe('header')
expect(response.headers.get('transfer-encoding')).toBe('chunked')
expect(response.headers.get('content-type')).toBe(
'text/event-stream; charset=utf-8'
)
})

it('stop stream on canceled request', async () => {
const expected = ['a', 'b']

Expand Down

0 comments on commit 4667e3c

Please sign in to comment.