diff --git a/src/listener.ts b/src/listener.ts index d25f512..0215c29 100644 --- a/src/listener.ts +++ b/src/listener.ts @@ -53,12 +53,11 @@ const responseViaResponseObject = async ( res: Response | Promise, 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) { @@ -77,20 +76,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)) } @@ -115,7 +124,9 @@ export const getRequestListener = (fetchCallback: FetchCallback) => { const req = newRequest(incoming) try { - res = fetchCallback(req, { incoming, outgoing } as HttpBindings) as Response | Promise + res = fetchCallback(req, { incoming, outgoing } as HttpBindings) as + | Response + | Promise if (cacheKey in res) { // synchronous, cacheable response return responseViaCache(res as Response, outgoing)