Skip to content

Commit

Permalink
minor improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
nitedani committed Aug 1, 2024
1 parent 429eef1 commit ea89785
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 23 deletions.
16 changes: 2 additions & 14 deletions packages/vike-node/src/runtime/adapters/connectToWeb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Response | undefined> => {
return (request: Request): Promise<Response | undefined> => {
const req = createIncomingMessage(request)
const { res, onReadable } = createServerResponse(req)

Expand Down Expand Up @@ -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)
})
}
}
Expand Down
19 changes: 10 additions & 9 deletions packages/vike-node/src/runtime/adapters/createServerResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
)

Expand All @@ -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
Expand Down

0 comments on commit ea89785

Please sign in to comment.