Skip to content

Commit

Permalink
fix(proxyRequest): merge input headers into default headers
Browse files Browse the repository at this point in the history
  • Loading branch information
gemmadlou committed Aug 29, 2024
1 parent af4b22c commit 019f0e8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/utils/internal/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,17 @@ export function rewriteCookieProperty(
export function mergeHeaders(
defaults: HeadersInit,
...inputs: (HeadersInit | RequestHeaders | undefined)[]
) {
): HeadersInit | Headers {
const _inputs = inputs.filter(Boolean) as HeadersInit[];
if (_inputs.length === 0) {
return defaults;
}

const merged = new Headers(defaults);
for (const input of _inputs) {
for (const [key, value] of Object.entries(input!)) {
const entries =
input instanceof Headers ? input.entries() : Object.entries(input!);
for (const [key, value] of entries) {
if (value !== undefined) {
merged.set(key, value);
}
Expand Down
24 changes: 24 additions & 0 deletions test/proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { vi, beforeEach } from "vitest";
import { setCookie } from "../src";
import { proxy, proxyRequest } from "../src/utils/proxy";
import { describeMatrix } from "./_setup";
import { mergeHeaders } from "../src/utils/internal/proxy";

describeMatrix("proxy", (t, { it, expect, describe }) => {
const spy = vi.spyOn(console, "error");
Expand Down Expand Up @@ -187,6 +188,29 @@ describeMatrix("proxy", (t, { it, expect, describe }) => {
},
60 * 1000,
);

it("can merge input headers into the default", async () => {
t.app.all("/test-headers", async (event) => {
const headers = new Headers();

headers.set("Authorization", "Bearer 1234");
headers.set("X-Domain", "abcd");

const mergedHeaders = mergeHeaders(event.request.headers, headers);

return {
headers:
mergedHeaders instanceof Headers
? Object.fromEntries(mergedHeaders.entries())
: Object.entries(mergedHeaders),
};
});

const result = await t.fetch("/test-headers").then((r) => r.json());

expect(result.headers["authorization"]).toEqual("Bearer 1234");
expect(result.headers["x-domain"]).toEqual("abcd");
});
});

describe("multipleCookies", () => {
Expand Down

0 comments on commit 019f0e8

Please sign in to comment.