Skip to content

Commit 82f0180

Browse files
committed
Clean up adding headers and multiple Response objects
1 parent fc400b3 commit 82f0180

File tree

1 file changed

+19
-27
lines changed

1 file changed

+19
-27
lines changed

src/startServerAndCreateNextHandler.ts

+19-27
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ function startServerAndCreateNextHandler<
3636
},
3737
});
3838

39+
const headers: Record<string, string> = {};
40+
for (const [key, value] of httpGraphQLResponse.headers) {
41+
headers[key] = value;
42+
}
43+
3944
if (isNextApiRequest(req)) {
4045
if (!res) {
4146
throw new Error('API Routes require you to pass both the req and res object.');
@@ -50,9 +55,7 @@ function startServerAndCreateNextHandler<
5055
if (httpGraphQLResponse.body.kind === 'complete') {
5156
res.send(httpGraphQLResponse.body.string);
5257
} else {
53-
res.writeHead(200, {
54-
'Content-Type': 'multipart/mixed; boundary="-"',
55-
});
58+
res.writeHead(200, headers);
5659

5760
for await (const chunk of httpGraphQLResponse.body.asyncIterator) {
5861
res.write(chunk);
@@ -63,36 +66,25 @@ function startServerAndCreateNextHandler<
6366
return;
6467
}
6568

66-
const headers: Record<string, string> = {};
67-
for (const [key, value] of httpGraphQLResponse.headers) {
68-
headers[key] = value;
69-
}
69+
let responseObject: string | ReadableStream;
7070

7171
if (httpGraphQLResponse.body.kind === 'complete') {
72-
// eslint-disable-next-line consistent-return
73-
return new Response(httpGraphQLResponse.body.string, {
74-
headers,
75-
status: httpGraphQLResponse.status || 200,
72+
responseObject = httpGraphQLResponse.body.string;
73+
} else {
74+
const responseBody = httpGraphQLResponse.body;
75+
responseObject = new ReadableStream({
76+
async start(controller) {
77+
for await (const chunk of responseBody.asyncIterator) {
78+
controller.enqueue(chunk);
79+
}
80+
controller.close();
81+
},
7682
});
7783
}
7884

79-
const responseBody = httpGraphQLResponse.body;
80-
const stream = new ReadableStream({
81-
async start(controller) {
82-
for await (const chunk of responseBody.asyncIterator) {
83-
controller.enqueue(chunk);
84-
}
85-
controller.close();
86-
},
87-
});
88-
8985
// eslint-disable-next-line consistent-return
90-
return new Response(stream, {
91-
headers: {
92-
...headers,
93-
'Content-Type': 'application/json',
94-
'Transfer-Encoding': 'chunked',
95-
},
86+
return new Response(responseObject, {
87+
headers,
9688
status: httpGraphQLResponse.status || 200,
9789
});
9890
}

0 commit comments

Comments
 (0)