diff --git a/packages/vike-node/src/runtime/adapters/connectToWeb.ts b/packages/vike-node/src/runtime/adapters/connectToWeb.ts index 11a77ce..944fd19 100644 --- a/packages/vike-node/src/runtime/adapters/connectToWeb.ts +++ b/packages/vike-node/src/runtime/adapters/connectToWeb.ts @@ -26,7 +26,7 @@ const statusCodesWithoutBody = [ * @returns {WebHandler} A function that handles web requests and returns a Response or undefined. */ function connectToWeb(handler: ConnectMiddleware): WebHandler { - return async (request: Request): Promise => { + return (request: Request): Promise => { const req = createIncomingMessage(request) const { res, onReadable } = createServerResponse(req) @@ -56,19 +56,7 @@ function connectToWeb(handler: ConnectMiddleware): WebHandler { } } - try { - handler(req, res, next) - } catch (error) { - reject(error instanceof Error ? error : new Error(String(error))) - } - - request.signal.addEventListener( - 'abort', - () => { - resolve(undefined) - }, - { once: true } - ) + Promise.resolve(handler(req, res, next)).catch(next) }) } } diff --git a/packages/vike-node/src/runtime/adapters/createServerResponse.ts b/packages/vike-node/src/runtime/adapters/createServerResponse.ts index 46799ca..6235b5c 100644 --- a/packages/vike-node/src/runtime/adapters/createServerResponse.ts +++ b/packages/vike-node/src/runtime/adapters/createServerResponse.ts @@ -17,12 +17,18 @@ function createServerResponse(incomingMessage: IncomingMessage) { const passThrough = new PassThrough() const onReadable = new Promise<{ readable: Readable; headers: OutgoingHttpHeaders; statusCode: number }>( (resolve, reject) => { - passThrough.once('readable', () => { + const handleReadable = () => { resolve({ readable: Readable.from(passThrough), headers: res.getHeaders(), statusCode: res.statusCode }) - }) - passThrough.once('error', (err) => { + } + + const handleError = (err: Error) => { reject(err) - }) + } + + passThrough.once('readable', handleReadable) + passThrough.once('end', handleReadable) + passThrough.once('error', handleError) + res.once('error', handleError) } ) @@ -37,16 +43,11 @@ function createServerResponse(incomingMessage: IncomingMessage) { res.write = passThrough.write.bind(passThrough) res.end = (passThrough as any).end.bind(passThrough) - let headersSet = false res.writeHead = function writeHead( statusCode: number, statusMessage?: string | OutgoingHttpHeaders | OutgoingHttpHeader[], headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] ): ServerResponse { - if (headersSet) { - return res - } - headersSet = true res.statusCode = statusCode if (typeof statusMessage === 'object') { headers = statusMessage