From cb33108a33a5952f21e5f67eca11744d76177fd6 Mon Sep 17 00:00:00 2001 From: Wyatt Johnson Date: Fri, 13 Oct 2023 22:38:24 -0600 Subject: [PATCH] fix: prefer async iteration vs callbacks --- .../src/experimental/testmode/proxy/server.ts | 19 ++++++++----------- .../src/server/app-render/action-handler.ts | 15 ++++----------- packages/next/src/server/body-streams.ts | 9 ++++----- 3 files changed, 16 insertions(+), 27 deletions(-) diff --git a/packages/next/src/experimental/testmode/proxy/server.ts b/packages/next/src/experimental/testmode/proxy/server.ts index fcf9f851bce45..6139d44ffc94e 100644 --- a/packages/next/src/experimental/testmode/proxy/server.ts +++ b/packages/next/src/experimental/testmode/proxy/server.ts @@ -5,17 +5,14 @@ import { UNHANDLED } from './types' import type { FetchHandler } from './fetch-api' import { handleFetch } from './fetch-api' -function readBody(req: IncomingMessage): Promise { - return new Promise((resolve, reject) => { - const acc: Buffer[] = [] - req.on('data', (chunk) => { - acc.push(chunk) - }) - req.on('end', () => { - resolve(Buffer.concat(acc)) - }) - req.on('error', reject) - }) +async function readBody(req: IncomingMessage): Promise { + const acc: Buffer[] = [] + + for await (const chunk of req) { + acc.push(chunk) + } + + return Buffer.concat(acc) } export async function createProxyServer({ diff --git a/packages/next/src/server/app-render/action-handler.ts b/packages/next/src/server/app-render/action-handler.ts index 05d1a88e9b74b..f36042753874a 100644 --- a/packages/next/src/server/app-render/action-handler.ts +++ b/packages/next/src/server/app-render/action-handler.ts @@ -46,18 +46,11 @@ function nodeToWebReadableStream(nodeReadable: import('stream').Readable) { } return new ReadableStream({ - start(controller) { - nodeReadable.on('data', (chunk) => { + start: async (controller) => { + for await (const chunk of nodeReadable) { controller.enqueue(chunk) - }) - - nodeReadable.on('end', () => { - controller.close() - }) - - nodeReadable.on('error', (error) => { - controller.error(error) - }) + } + controller.close() }, }) } else { diff --git a/packages/next/src/server/body-streams.ts b/packages/next/src/server/body-streams.ts index c4d3687766a3d..b0ab4f6012820 100644 --- a/packages/next/src/server/body-streams.ts +++ b/packages/next/src/server/body-streams.ts @@ -8,12 +8,11 @@ export function requestToBodyStream( stream: Readable ) { return new context.ReadableStream({ - start(controller) { - stream.on('data', (chunk) => + start: async (controller) => { + for await (const chunk of stream) { controller.enqueue(new KUint8Array([...new Uint8Array(chunk)])) - ) - stream.on('end', () => controller.close()) - stream.on('error', (err) => controller.error(err)) + } + controller.close() }, }) }