source: trip-planner-front/node_modules/needle/lib/querystring.js@ 188ee53

Last change on this file since 188ee53 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.3 KB
Line 
1// based on the qs module, but handles null objects as expected
2// fixes by Tomas Pollak.
3
4var toString = Object.prototype.toString;
5
6function 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
24function 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
37function 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
49exports.build = stringify;
Note: See TracBrowser for help on using the repository browser.