Skip to content

Commit

Permalink
refactor: more readable (#132)
Browse files Browse the repository at this point in the history
  • Loading branch information
jarqvi authored Jan 29, 2024
1 parent f2042d7 commit f2b851c
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,11 @@ const responseViaResponseObject = async (
res: Response | Promise<Response>,
outgoing: ServerResponse | Http2ServerResponse
) => {
if (res instanceof Promise) {
res = await res.catch(handleFetchError)
}
res = res instanceof Promise ? await res.catch(handleFetchError) : res

try {
if (cacheKey in res) {
const isCached = cacheKey in res
if (isCached) {
return responseViaCache(res as Response, outgoing)
}
} catch (e: unknown) {
Expand All @@ -79,20 +78,30 @@ const responseViaResponseObject = async (
* Else if content-type is not application/json nor text/* but can be text/event-stream,
* we assume that the response should be streamed.
*/

const {
'transfer-encoding': transferEncoding,
'content-encoding': contentEncoding,
'content-length': contentLength,
'x-accel-buffering': accelBuffering,
'content-type': contentType,
} = resHeaderRecord

if (
resHeaderRecord['transfer-encoding'] ||
resHeaderRecord['content-encoding'] ||
resHeaderRecord['content-length'] ||
transferEncoding ||
contentEncoding ||
contentLength ||
// nginx buffering variant
(resHeaderRecord['x-accel-buffering'] &&
regBuffer.test(resHeaderRecord['x-accel-buffering'] as string)) ||
!regContentType.test(resHeaderRecord['content-type'] as string)
(accelBuffering && regBuffer.test(accelBuffering as string)) ||
!regContentType.test(contentType as string)
) {
outgoing.writeHead(res.status, resHeaderRecord)

await writeFromReadableStream(res.body, outgoing)
} else {
const buffer = await res.arrayBuffer()
resHeaderRecord['content-length'] = buffer.byteLength

outgoing.writeHead(res.status, resHeaderRecord)
outgoing.end(new Uint8Array(buffer))
}
Expand Down

0 comments on commit f2b851c

Please sign in to comment.