Skip to content

Commit

Permalink
Merge pull request #37 from mjackson/response_headers
Browse files Browse the repository at this point in the history
feat: use object instead of array for sending headers
  • Loading branch information
mjackson authored Dec 9, 2024
2 parents bbf4264 + 47a2d6b commit 5db52c2
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
1 change: 1 addition & 0 deletions packages/node-fetch-server/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ This is the changelog for [`node-fetch-server`](https://github.com/mjackson/remi
## HEAD

- Expose `createHeaders(req: http.IncomingMessage): Headers` API for creating headers from the headers of incoming request objects.
- Update `sendResponse` to use an object to add support for libraries such as express while maintaining `node:http` and `node:https` compatibility.

## v0.4.1 (2024-12-04)

Expand Down
12 changes: 4 additions & 8 deletions packages/node-fetch-server/src/lib/request-listener.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,14 +169,10 @@ describe('createRequestListener', () => {
});

mock.method(res, 'end', () => {
assert.deepEqual(headers, [
'content-type',
'text/plain',
'set-cookie',
'a=1',
'set-cookie',
'b=2',
]);
assert.deepEqual(headers, {
'content-type': 'text/plain',
'set-cookie': ['a=1', 'b=2'],
});
resolve();
});

Expand Down
12 changes: 10 additions & 2 deletions packages/node-fetch-server/src/lib/request-listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,17 @@ export async function sendResponse(res: http.ServerResponse, response: Response)
// Use the rawHeaders API and iterate over response.headers so we are sure to send multiple
// Set-Cookie headers correctly. These would incorrectly be merged into a single header if we
// tried to use `Object.fromEntries(response.headers.entries())`.
let rawHeaders: string[] = [];
let rawHeaders: Record<string, string | string[]> = {};
for (let [key, value] of response.headers) {
rawHeaders.push(key, value);
if (key in rawHeaders) {
if (Array.isArray(rawHeaders[key])) {
rawHeaders[key].push(value);
} else {
rawHeaders[key] = [rawHeaders[key] as string, value];
}
} else {
rawHeaders[key] = value;
}
}

res.writeHead(response.status, rawHeaders);
Expand Down

0 comments on commit 5db52c2

Please sign in to comment.