Skip to content
Closed
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
15 changes: 8 additions & 7 deletions src/listener.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import type { IncomingMessage, ServerResponse, OutgoingHttpHeaders } from 'node:http'
import type { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from 'node:http'
import { Http2ServerRequest } from 'node:http2'
import type { Http2ServerResponse } from 'node:http2'
import type { IncomingMessageWithWrapBodyStream } from './request'
import {
Request as LightweightRequest,
abortControllerKey,
newRequest,
Request as LightweightRequest,
wrapBodyStream,
toRequestError,
wrapBodyStream,
} from './request'
import { cacheKey, Response as LightweightResponse } from './response'
import { Response as LightweightResponse, cacheKey } from './response'
import type { InternalCache } from './response'
import type { CustomErrorHandler, FetchCallback, HttpBindings } from './types'
import { writeFromReadableStream, buildOutgoingHttpHeaders } from './utils'
import { buildOutgoingHttpHeaders, writeFromReadableStream } from './utils'
import { X_ALREADY_SENT } from './utils/response/constants'
import './globals'

Expand Down Expand Up @@ -125,7 +125,7 @@ const responseViaResponseObject = async (
/**
* If content-encoding is set, we assume that the response should be not decoded.
* Else if transfer-encoding is set, we assume that the response should be streamed.
* Else if content-length is set, we assume that the response content has been taken care of.
* Else if content-length and etag are not set, we assume that the response should be streamed.
* Else if x-accel-buffering is set to no, we assume that the response should be streamed.
* Else if content-type is not application/json nor text/* but can be text/event-stream,
* we assume that the response should be streamed.
Expand All @@ -137,12 +137,13 @@ const responseViaResponseObject = async (
'content-length': contentLength,
'x-accel-buffering': accelBuffering,
'content-type': contentType,
etag,
} = resHeaderRecord

if (
transferEncoding ||
contentEncoding ||
contentLength ||
(!contentLength && !etag) ||
// nginx buffering variant
(accelBuffering && regBuffer.test(accelBuffering as string)) ||
!regContentType.test(contentType as string)
Expand Down
62 changes: 60 additions & 2 deletions test/listener.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ describe('Error handling - sync fetchCallback', () => {

it('Should set the response if error handler returns a response', async () => {
errorHandler.mockImplementationOnce((err: Error) => {
return new Response(`${err}`, { status: 500, headers: { 'my-custom-header': 'hi' } })
return new Response(`${err}`, {
status: 500,
headers: { 'my-custom-header': 'hi' },
})
})

const res = await request(server).get('/throw-error')
Expand Down Expand Up @@ -148,7 +151,10 @@ describe('Error handling - async fetchCallback', () => {

it('Should set the response if error handler returns a response', async () => {
errorHandler.mockImplementationOnce((err: Error) => {
return new Response(`${err}`, { status: 500, headers: { 'my-custom-header': 'hi' } })
return new Response(`${err}`, {
status: 500,
headers: { 'my-custom-header': 'hi' },
})
})

const res = await request(server).get('/throw-error')
Expand Down Expand Up @@ -344,3 +350,55 @@ describe('overrideGlobalObjects', () => {
})
})
})

describe('ReadableStream response body', () => {
it('Should stream response when body is a ReadableStream', async () => {
const streamData = 'Hello, streaming world!'
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder()
controller.enqueue(encoder.encode(streamData))
controller.close()
},
})

const fetchCallback = jest.fn(() => {
return new Response(stream, {
headers: { 'content-type': 'text/plain' },
})
})

const requestListener = getRequestListener(fetchCallback)
const server = createServer(requestListener)

const res = await request(server).get('/stream').send()
expect(res.status).toBe(200)
expect(res.text).toBe(streamData)
expect(res.headers['content-type']).toBe('text/plain')
})

it('Should stream response when body is ReadableStream even with application/json content-type', async () => {
const jsonData = { message: 'streaming json' }
const stream = new ReadableStream({
start(controller) {
const encoder = new TextEncoder()
controller.enqueue(encoder.encode(JSON.stringify(jsonData)))
controller.close()
},
})

const fetchCallback = jest.fn(() => {
return new Response(stream, {
headers: { 'content-type': 'application/json' },
})
})

const requestListener = getRequestListener(fetchCallback)
const server = createServer(requestListener)

const res = await request(server).get('/stream-json').send()
expect(res.status).toBe(200)
expect(res.body).toEqual(jsonData)
expect(res.headers['content-type']).toBe('application/json')
})
})