Adrià Vilanova MartÃnez | 9c418ab | 2024-12-05 15:34:40 +0100 | [diff] [blame] | 1 | export default class FetchHeaders { |
| 2 | constructor(private headers: HeadersInit | undefined) {} |
| 3 | |
| 4 | hasValue(name: string, value: string) { |
| 5 | if (!this.headers) { |
| 6 | return false; |
| 7 | } else if (this.headers instanceof Headers) { |
| 8 | return this.headers.get(name) == value; |
| 9 | } else { |
| 10 | const headersArray = Array.isArray(this.headers) |
| 11 | ? this.headers |
| 12 | : Object.entries(this.headers); |
| 13 | return headersArray.some( |
| 14 | ([candidateHeaderName, candidateValue]) => |
| 15 | this.isEqualCaseInsensitive(candidateHeaderName, name) && |
| 16 | candidateValue === value, |
| 17 | ); |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | removeHeader(name: string) { |
| 22 | if (!this.headers) { |
| 23 | return; |
| 24 | } else if (this.headers instanceof Headers) { |
| 25 | this.headers.delete(name); |
| 26 | } else if (Array.isArray(this.headers)) { |
| 27 | const index = this.headers.findIndex(([candidateHeaderName]) => |
| 28 | this.isEqualCaseInsensitive(candidateHeaderName, name), |
| 29 | ); |
| 30 | if (index !== -1) delete this.headers[index]; |
| 31 | } else { |
| 32 | const headerNames = Object.keys(this.headers); |
| 33 | const headerName = headerNames.find((candidateName) => |
| 34 | this.isEqualCaseInsensitive(candidateName, name), |
| 35 | ); |
| 36 | if (headerName) delete this.headers[headerName]; |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | private isEqualCaseInsensitive(a: string, b: string) { |
| 41 | return ( |
| 42 | a.localeCompare(b, undefined, { |
| 43 | sensitivity: 'accent', |
| 44 | }) == 0 |
| 45 | ); |
| 46 | } |
| 47 | } |