Skip to content

Commit

Permalink
fix(proxy): merge overriden headers with different case (#476)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Aug 1, 2023
1 parent cdd2680 commit 4de6335
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 11 deletions.
33 changes: 25 additions & 8 deletions src/utils/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,22 +51,20 @@ export async function proxyRequest(
}

// Headers
const headers = getProxyRequestHeaders(event);
if (opts.fetchOptions?.headers) {
Object.assign(headers, opts.fetchOptions.headers);
}
if (opts.headers) {
Object.assign(headers, opts.headers);
}
const fetchHeaders = mergeHeaders(
getProxyRequestHeaders(event),
opts.fetchOptions?.headers,
opts.headers
);

return sendProxy(event, target, {
...opts,
fetchOptions: {
headers,
method,
body,
duplex,
...opts.fetchOptions,
headers: fetchHeaders,
},
});
}
Expand Down Expand Up @@ -222,3 +220,22 @@ function rewriteCookieProperty(
}
);
}

function mergeHeaders(
defaults: HeadersInit,
...inputs: (HeadersInit | RequestHeaders | undefined)[]
) {
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!)) {
if (value !== undefined) {
merged.set(key, value);
}
}
}
return merged;
}
18 changes: 15 additions & 3 deletions test/proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,13 @@ describe("", () => {
app.use(
"/",
eventHandler((event) => {
return proxyRequest(event, url + "/debug", { fetch });
return proxyRequest(event, url + "/debug", {
fetch,
headers: { "x-custom1": "overriden" },
fetchOptions: {
headers: { "x-custom2": "overriden" },
},
});
})
);

Expand All @@ -96,13 +102,19 @@ describe("", () => {
body: "hello",
headers: {
"content-type": "text/custom",
"x-custom": "hello",
"X-Custom1": "user",
"X-Custom2": "user",
"X-Custom3": "user",
},
}).then((r) => r.json());

const { headers, ...data } = result;
expect(headers["content-type"]).toEqual("text/custom");
expect(headers["x-custom"]).toEqual("hello");

expect(headers["x-custom1"]).toEqual("overriden");
expect(headers["x-custom2"]).toEqual("overriden");
expect(headers["x-custom3"]).toEqual("user");

expect(data).toMatchInlineSnapshot(`
{
"body": "hello",
Expand Down

0 comments on commit 4de6335

Please sign in to comment.