Skip to content

Commit

Permalink
perf: polish listener.ts (#92)
Browse files Browse the repository at this point in the history
* perf: polish `listener.ts`

* add a comment
  • Loading branch information
yusukebe authored Nov 12, 2023
1 parent 6257b7e commit 311a2a0
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import type { ReadableStream as NodeReadableStream } from 'node:stream/web'
import type { FetchCallback } from './types'
import './globals'

const regBuffer = /^no$/i
const regContentType = /^(application\/json\b|text\/(?!event-stream\b))/i

export const getRequestListener = (fetchCallback: FetchCallback) => {
return async (
incoming: IncomingMessage | Http2ServerRequest,
Expand Down Expand Up @@ -46,14 +49,9 @@ export const getRequestListener = (fetchCallback: FetchCallback) => {
}
}

const contentType = res.headers.get('content-type') || ''
// nginx buffering variant
const buffering = res.headers.get('x-accel-buffering') || ''
const contentEncoding = res.headers.get('content-encoding')
const contentLength = res.headers.get('content-length')
const transferEncoding = res.headers.get('transfer-encoding')

const resHeaderRecord: Record<string, string> = {}
for (const [k, v] of res.headers) {
resHeaderRecord[k] = v
if (k === 'set-cookie') {
// node native Headers.prototype has getSetCookie method
outgoing.setHeader(k, (res.headers as any).getSetCookie(k))
Expand All @@ -74,11 +72,12 @@ export const getRequestListener = (fetchCallback: FetchCallback) => {
* we assume that the response should be streamed.
*/
if (
contentEncoding ||
transferEncoding ||
contentLength ||
/^no$/i.test(buffering) ||
!/^(application\/json\b|text\/(?!event-stream\b))/i.test(contentType)
resHeaderRecord['transfer-encoding'] ||
resHeaderRecord['content-encoding'] ||
resHeaderRecord['content-length'] ||
// nginx buffering variant
regBuffer.test(resHeaderRecord['x-accel-buffering']) ||
!regContentType.test(resHeaderRecord['content-type'])
) {
await pipeline(Readable.fromWeb(res.body as NodeReadableStream), outgoing)
} else {
Expand Down

0 comments on commit 311a2a0

Please sign in to comment.