1 | // based on the qs module, but handles null objects as expected
|
---|
2 | // fixes by Tomas Pollak.
|
---|
3 |
|
---|
4 | var toString = Object.prototype.toString;
|
---|
5 |
|
---|
6 | function stringify(obj, prefix) {
|
---|
7 | if (prefix && (obj === null || typeof obj == 'undefined')) {
|
---|
8 | return prefix + '=';
|
---|
9 | } else if (toString.call(obj) == '[object Array]') {
|
---|
10 | return stringifyArray(obj, prefix);
|
---|
11 | } else if (toString.call(obj) == '[object Object]') {
|
---|
12 | return stringifyObject(obj, prefix);
|
---|
13 | } else if (toString.call(obj) == '[object Date]') {
|
---|
14 | return obj.toISOString();
|
---|
15 | } else if (prefix) { // string inside array or hash
|
---|
16 | return prefix + '=' + encodeURIComponent(String(obj));
|
---|
17 | } else if (String(obj).indexOf('=') !== -1) { // string with equal sign
|
---|
18 | return String(obj);
|
---|
19 | } else {
|
---|
20 | throw new TypeError('Cannot build a querystring out of: ' + obj);
|
---|
21 | }
|
---|
22 | };
|
---|
23 |
|
---|
24 | function stringifyArray(arr, prefix) {
|
---|
25 | var ret = [];
|
---|
26 |
|
---|
27 | for (var i = 0, len = arr.length; i < len; i++) {
|
---|
28 | if (prefix)
|
---|
29 | ret.push(stringify(arr[i], prefix + '[]'));
|
---|
30 | else
|
---|
31 | ret.push(stringify(arr[i]));
|
---|
32 | }
|
---|
33 |
|
---|
34 | return ret.join('&');
|
---|
35 | }
|
---|
36 |
|
---|
37 | function stringifyObject(obj, prefix) {
|
---|
38 | var ret = [];
|
---|
39 |
|
---|
40 | Object.keys(obj).forEach(function(key) {
|
---|
41 | ret.push(stringify(obj[key], prefix
|
---|
42 | ? prefix + '[' + encodeURIComponent(key) + ']'
|
---|
43 | : encodeURIComponent(key)));
|
---|
44 | })
|
---|
45 |
|
---|
46 | return ret.join('&');
|
---|
47 | }
|
---|
48 |
|
---|
49 | exports.build = stringify;
|
---|