Skip to content
Merged
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
71 changes: 47 additions & 24 deletions src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@ function newResponse(this: Response, body: BodyInit | null, init?: ResponseInit)
;(this as any).status = init?.status || 200
;(this as any).__body = body
;(this as any).__init = init
;(this as any).__cache = [body, (init?.headers || {}) as Record<string, string>]
if (typeof body !== 'string') {
delete (this as any).__cache
if (typeof body === 'string' || body instanceof ReadableStream) {
;(this as any).__cache = [body, (init?.headers || {}) as Record<string, string>]
}
}
newResponse.prototype = responsePrototype
Expand Down Expand Up @@ -113,22 +112,55 @@ const requestPrototype: Record<string, any> = {
})
})

const handleError = (e: unknown): Response =>
const handleFetchError = (e: unknown): Response =>
new Response(null, {
status:
e instanceof Error && (e.name === 'TimeoutError' || e.constructor.name === 'TimeoutError')
? 504 // timeout error emits 504 timeout
: 500,
})

const handleResponseError = (e: unknown, outgoing: ServerResponse | Http2ServerResponse) => {
const err = (e instanceof Error ? e : new Error('unknown error', { cause: e })) as Error & {
code: string
}
if (err.code === 'ERR_STREAM_PREMATURE_CLOSE') {
console.info('The user aborted a request.')
} else {
console.error(e)
outgoing.destroy(err)
}
}

const responseViaCache = (
res: Response,
outgoing: ServerResponse | Http2ServerResponse
): undefined | Promise<undefined> => {
const [body, header] = (res as any).__cache
outgoing.writeHead((res as Response).status, header)
if (typeof body === 'string') {
header['content-length'] ||= '' + Buffer.byteLength(body)
outgoing.end(body)
} else {
return writeFromReadableStream(body, outgoing)?.catch(
(e) => handleResponseError(e, outgoing) as undefined
)
}
}

const responseViaResponseObject = async (
res: Response | Promise<Response>,
outgoing: ServerResponse | Http2ServerResponse
) => {
try {
res = await res
} catch (e: unknown) {
res = handleError(e)
if (res instanceof Promise) {
res = await res.catch(handleFetchError)
}
if ('__cache' in res) {
try {
return responseViaCache(res as Response, outgoing)
} catch (e: unknown) {
return handleResponseError(e, outgoing)
}
}

const resHeaderRecord: OutgoingHttpHeaders = {}
Expand Down Expand Up @@ -172,15 +204,7 @@ const responseViaResponseObject = async (
outgoing.end(new Uint8Array(buffer))
}
} catch (e: unknown) {
const err = (e instanceof Error ? e : new Error('unknown error', { cause: e })) as Error & {
code: string
}
if (err.code === 'ERR_STREAM_PREMATURE_CLOSE') {
console.info('The user aborted a request.')
} else {
console.error(e)
outgoing.destroy(err)
}
handleResponseError(e, outgoing)
}
} else {
outgoing.writeHead(res.status, resHeaderRecord)
Expand All @@ -201,15 +225,14 @@ export const getRequestListener = (fetchCallback: FetchCallback) => {
try {
res = fetchCallback(req) as Response | Promise<Response>
if ('__cache' in res) {
// response via cache
const [body, header] = (res as any).__cache
header['content-length'] ||= '' + Buffer.byteLength(body)
outgoing.writeHead((res as Response).status, header)
outgoing.end(body)
return
return responseViaCache(res as Response, outgoing)
}
} catch (e: unknown) {
res = handleError(e)
if (!res) {
res = handleFetchError(e)
} else {
return handleResponseError(e, outgoing)
}
}

return responseViaResponseObject(res, outgoing)
Expand Down