Skip to content

Commit

Permalink
Changes to the incremental responses to ensure they stream the respon…
Browse files Browse the repository at this point in the history
…ses back instead of batching them all together
  • Loading branch information
jer-k committed Jul 29, 2024
1 parent 72185b5 commit 2288ed3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 17 deletions.
1 change: 0 additions & 1 deletion src/__tests__/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ describe('nextHandler', () => {
};
},
{
noIncrementalDelivery: true,
serverIsStartedInBackground: true,
},
);
Expand Down
37 changes: 21 additions & 16 deletions src/startServerAndCreateNextHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<string, string> = {};

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;
Expand Down

0 comments on commit 2288ed3

Please sign in to comment.