diff --git a/lib/querystring.js b/lib/querystring.js index 3c03cf313e..7ccd8cf49a 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -134,42 +134,34 @@ var stringifyPrimitive = function(v) { QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; - obj = (obj === null) ? undefined : obj; - - switch (typeof obj) { - case 'object': - return Object.keys(obj).map(function(k) { - if (Array.isArray(obj[k])) { - return obj[k].map(function(v) { - return QueryString.escape(stringifyPrimitive(k)) + - eq + - QueryString.escape(stringifyPrimitive(v)); - }).join(sep); - } else { - return QueryString.escape(stringifyPrimitive(k)) + - eq + - QueryString.escape(stringifyPrimitive(obj[k])); - } - }).join(sep); + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = QueryString.escape(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + QueryString.escape(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + QueryString.escape(stringifyPrimitive(obj[k])); + } + }).join(sep); - default: - if (!name) return ''; - return QueryString.escape(stringifyPrimitive(name)) + eq + - QueryString.escape(stringifyPrimitive(obj)); } + + if (!name) return ''; + return QueryString.escape(stringifyPrimitive(name)) + eq + + QueryString.escape(stringifyPrimitive(obj)); }; // Parse a key=val string. QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; - var obj = {}, - maxKeys = 1000; - - // Handle maxKeys = 0 case - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } + var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; @@ -178,19 +170,27 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { var regexp = /\+/g; qs = qs.split(sep); + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0) { - qs = qs.slice(0, maxKeys); + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; } - for (var i = 0, len = qs.length; i < len; ++i) { + for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), - kstr = x.substring(0, idx), - vstr = x.substring(idx + 1), k, v; + kstr, vstr, k, v; - if (kstr === '' && vstr !== '') { - kstr = vstr; + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; vstr = ''; } @@ -204,10 +204,10 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { if (!hasOwnProperty(obj, k)) { obj[k] = v; - } else if (!Array.isArray(obj[k])) { - obj[k] = [obj[k], v]; - } else { + } else if (Array.isArray(obj[k])) { obj[k].push(v); + } else { + obj[k] = [obj[k], v]; } }