unsplash-js icon indicating copy to clipboard operation
unsplash-js copied to clipboard

Spreading headers may lose data

Open OliverJAsh opened this issue 3 years ago • 0 comments

Related: https://github.com/unsplash/unsplash-web/pull/7397

https://github.com/unsplash/unsplash-js/blob/07050e9d8d7d3655e7ca1981a8db8a827a3c6745/src/helpers/request.ts#L37-L40

The type of the headers variable that we're spreading here is HeadersInit | undefined.

HeadersInit is defined as:

type HeadersInit = string[][] | Record<string, string> | Headers;

What happens when we merge an array (string[][]) into an object? The array indexes become header keys. That's not the correct behaviour—we should instead use the key inside the entries array.

const a = [['a', '1']]
const b = { ...a }
JSON.stringify(b)
// => '{"0":["a","1"]}'

Desired result: { a: 1 }

What happens when we merge a Headers class into an object? We lose all data!

const a = new Headers([['a', '1']])
const b = { ...a }
JSON.stringify(b)
// => '{}'

Desired result: { a: 1 }

Related: a lint rule could have caught this https://github.com/typescript-eslint/typescript-eslint/issues/748

OliverJAsh avatar Dec 15 '21 14:12 OliverJAsh