/
parse-http-header.js
52 lines (44 loc) · 1.1 KB
/
parse-http-header.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
function Param (string) {
var SEPARATOR = /(?:;|,)/g
, OPERATOR = /=/;
if (string && SEPARATOR.test(string)) {
var split = string.split(SEPARATOR);
if (OPERATOR.test(string)) {
split.forEach(function (param, idx) {
var parts = param.split(OPERATOR).map(function (part) {
return part.trim();
});
if (parts.length === 2) {
this[parts[0]] || (this[parts[0]] = {});
this[parts[0]] = parts[1];
this[idx] = {};
this[idx][parts[0]] = parts[1];
}
else {
this[idx] = param;
}
}, this);
} else {
this[0] = split[0];
}
} else {
this[0] = string;
}
return this;
}
Param.prototype.toArray = function () {
return Object.keys(this).filter(function (key) {
return !isNaN(+key);
}).map(function (key) {
return this[key];
}, this);
};
/**
* Parse parameterized HTTP header value string into an object
*/
module.exports = function parseHttpHeader (string) {
Param.prototype.toString = function toString () {
return string;
};
return new Param(string);
};