forked from JakeChampion/fetch
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathHeaders.js
100 lines (78 loc) · 2.29 KB
/
Headers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
function normalizeName(name) {
if (typeof name !== "string") {
name = String(name);
}
name = name.trim();
if (name.length === 0) {
throw new TypeError("Header field name is empty");
}
if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name)) {
throw new TypeError(`Invalid character in header field name: ${name}`);
}
return name.toLowerCase();
}
function normalizeValue(value) {
if (typeof value !== "string") {
value = String(value);
}
return value;
}
class Headers {
map = new Map();
constructor(init = {}) {
if (init instanceof Headers) {
init.forEach(function (value, name) {
this.append(name, value);
}, this);
return this;
}
if (Array.isArray(init)) {
init.forEach(function ([name, value]) {
this.append(name, value);
}, this);
return this;
}
Object.getOwnPropertyNames(init).forEach((name) =>
this.append(name, init[name])
);
}
append(name, value) {
name = normalizeName(name);
value = normalizeValue(value);
const oldValue = this.get(name);
// From MDN: If the specified header already exists and accepts multiple values, append() will append the new value to the end of the value set.
// However, we're a missing a check on whether the header does indeed accept multiple values
this.map.set(name, oldValue ? oldValue + ", " + value : value);
}
delete(name) {
this.map.delete(normalizeName(name));
}
get(name) {
name = normalizeName(name);
return this.has(name) ? this.map.get(name) : null;
}
has(name) {
return this.map.has(normalizeName(name));
}
set(name, value) {
this.map.set(normalizeName(name), normalizeValue(value));
}
forEach(callback, thisArg) {
this.map.forEach(function (value, name) {
callback.call(thisArg, value, name, this);
}, this);
}
keys() {
return this.map.keys();
}
values() {
return this.map.values();
}
entries() {
return this.map.entries();
}
[Symbol.iterator]() {
return this.entries();
}
}
export default Headers;