headers.js
1.42 KB
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
/**
* HTTP Headers.
*/
import { each, trim, toLower } from '../util';
export default class Headers {
constructor(headers) {
this.map = {};
each(headers, (value, name) => this.append(name, value));
}
has(name) {
return getName(this.map, name) !== null;
}
get(name) {
var list = this.map[getName(this.map, name)];
return list ? list[0] : null;
}
getAll(name) {
return this.map[getName(this.map, name)] || [];
}
set(name, value) {
this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)];
}
append(name, value){
var list = this.getAll(name);
if (list.length) {
list.push(trim(value));
} else {
this.set(name, value);
}
}
delete(name){
delete this.map[getName(this.map, name)];
}
deleteAll(){
this.map = {};
}
forEach(callback, thisArg) {
each(this.map, (list, name) => {
each(list, value => callback.call(thisArg, value, name, this));
});
}
}
function getName(map, name) {
return Object.keys(map).reduce((prev, curr) => {
return toLower(name) === toLower(curr) ? curr : prev;
}, null);
}
function normalizeName(name) {
if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name');
}
return trim(name);
}