-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
105 lines (85 loc) · 1.71 KB
/
index.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
101
102
103
104
105
/**
* Module dependencies.
*/
var trim = require('trim');
var type = require('type');
var pattern = /(\w+)\[(\d+)\]/;
/**
* Safely encode the given string
*
* @param {String} str
* @return {String}
* @api private
*/
var encode = function(str) {
try {
return encodeURIComponent(str);
} catch (e) {
return str;
}
};
/**
* Safely decode the string
*
* @param {String} str
* @return {String}
* @api private
*/
var decode = function(str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
}
/**
* Parse the given query `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(str){
if ('string' != typeof str) return {};
str = trim(str);
if ('' == str) return {};
if ('?' == str.charAt(0)) str = str.slice(1);
var obj = {};
var pairs = str.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
var key = decode(parts[0]);
var m;
if (m = pattern.exec(key)) {
obj[m[1]] = obj[m[1]] || [];
obj[m[1]][m[2]] = decode(parts[1]);
continue;
}
obj[parts[0]] = null == parts[1]
? ''
: decode(parts[1]);
}
return obj;
};
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api public
*/
exports.stringify = function(obj){
if (!obj) return '';
var pairs = [];
for (var key in obj) {
var value = obj[key];
if ('array' == type(value)) {
for (var i = 0; i < value.length; ++i) {
pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i]));
}
continue;
}
pairs.push(encode(key) + '=' + encode(obj[key]));
}
return pairs.join('&');
};