From 2288ed3e676e59ff91e58d35096b958ee7523e46 Mon Sep 17 00:00:00 2001 From: jer-k Date: Fri, 19 Jul 2024 12:17:56 -0700 Subject: [PATCH] Changes to the incremental responses to ensure they stream the responses back instead of batching them all together --- src/__tests__/integration.test.ts | 1 - src/startServerAndCreateNextHandler.ts | 37 +++++++++++++++----------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/__tests__/integration.test.ts b/src/__tests__/integration.test.ts index cb232de..5bfafec 100644 --- a/src/__tests__/integration.test.ts +++ b/src/__tests__/integration.test.ts @@ -56,7 +56,6 @@ describe('nextHandler', () => { }; }, { - noIncrementalDelivery: true, serverIsStartedInBackground: true, }, ); diff --git a/src/startServerAndCreateNextHandler.ts b/src/startServerAndCreateNextHandler.ts index 7b7d951..dff239f 100644 --- a/src/startServerAndCreateNextHandler.ts +++ b/src/startServerAndCreateNextHandler.ts @@ -4,6 +4,7 @@ import { isNextApiRequest } from './lib/isNextApiRequest'; import { ApolloServer, BaseContext, ContextFunction } from '@apollo/server'; import { NextApiRequest, NextApiResponse } from 'next'; import { NextRequest } from 'next/server'; +import { Readable } from 'stream'; import { parse } from 'url'; type HandlerRequest = NextApiRequest | NextRequest | Request; @@ -49,34 +50,38 @@ function startServerAndCreateNextHandler< if (httpGraphQLResponse.body.kind === 'complete') { res.send(httpGraphQLResponse.body.string); + res.end(); } else { - for await (const chunk of httpGraphQLResponse.body.asyncIterator) { - res.write(chunk); - } + res.send(Readable.from(httpGraphQLResponse.body.asyncIterator)); } - res.end(); return; } - const body = []; - - if (httpGraphQLResponse.body.kind === 'complete') { - body.push(httpGraphQLResponse.body.string); - } else { - for await (const chunk of httpGraphQLResponse.body.asyncIterator) { - body.push(chunk); - } - } - const headers: Record = {}; - for (const [key, value] of httpGraphQLResponse.headers) { headers[key] = value; } // eslint-disable-next-line consistent-return - return new Response(body.join(''), { headers, status: httpGraphQLResponse.status || 200 }); + return new Response( + httpGraphQLResponse.body.kind === 'complete' + ? httpGraphQLResponse.body.string + : new ReadableStream({ + async pull(controller) { + if (httpGraphQLResponse.body.kind === 'chunked') { + const { value, done } = await httpGraphQLResponse.body.asyncIterator.next(); + + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + } + }, + }), + { headers, status: httpGraphQLResponse.status || 200 }, + ); } return handler;