elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

Headers merging issue when using fetch headers object #205

Closed Phoenixmatrix closed 12 months ago

Phoenixmatrix commented 1 year ago

The headers merging logic assumes JavaScript objects and key value pairs. The TypeScript types though allow using fetch Headers. When using fetch Headers, since they're not plain object, anything that sets headers will override them (eg: using a .post with an object as argument, or the .content helper).

I think the easiest fix is to tweak the types as to now allow fetch Headers as argument in the types, but alternatively a slightly smarter merge logic that accounts for Headers object would work too. Threw me in for a loop digging why my authorization headers were going poof right before a post request but not a get.

elbywan commented 12 months ago

Hey @Phoenixmatrix,

The headers merging logic assumes JavaScript objects and key value pairs. The TypeScript types though allow using fetch Headers. When using fetch Headers

Thanks for reporting this issue, I just published v2.7.1 which now converts the headers() argument to a record and will merge properly no matter the type.

const headers1 = new Headers({ "hello": "world" });
const headers2 = new Headers({ "bonjour": "le monde" });
const headers3 = { "hola": "mundo " };
const headers4 = [["hallo", "welt"]]

let w = wretch().headers(headers1);
console.log(w._options.headers);
// Object { hello: "world" }
w = w.headers(headers2);
console.log(w._options.headers);
// Object { hello: "world", bonjour: "le monde" }
w = w.headers(headers3);
console.log(w._options.headers);
// Object { hello: "world", bonjour: "le monde", hola: "mundo " }
w = w.headers(headers4);
console.log(w._options.headers);
// Object { hello: "world", bonjour: "le monde", hola: "mundo ", hallo: "welt" }

Threw me in for a loop digging why my authorization headers were going poof right before a post request but not a get.

And sorry about this 😬

Phoenixmatrix commented 12 months ago

Awesome, thank you so much!