From 229b0e9d38f18ccf37733d117114b8d3cabb8688 Mon Sep 17 00:00:00 2001 From: Marco Arduini Date: Tue, 27 Jun 2017 19:56:53 +0200 Subject: [PATCH] Handle stringifying empty objects with addQueryPrefix Stringifying an empty object would produce a string such as '?'. With this fix, we output an empty line instead. --- .eslintrc | 4 ++-- lib/stringify.js | 3 ++- test/stringify.js | 5 +++++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.eslintrc b/.eslintrc index 52e4416c..9309ed5b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -4,12 +4,12 @@ "extends": "@ljharb", "rules": { - "complexity": [2, 27], + "complexity": [2, 28], "consistent-return": 1, "id-length": [2, { "min": 1, "max": 25, "properties": "never" }], "indent": [2, 4], "max-params": [2, 12], - "max-statements": [2, 44], + "max-statements": [2, 45], "no-continue": 1, "no-magic-numbers": 0, "no-restricted-syntax": [2, "BreakStatement", "DebuggerStatement", "ForInStatement", "LabeledStatement", "WithStatement"], diff --git a/lib/stringify.js b/lib/stringify.js index 9a351111..036f18b7 100644 --- a/lib/stringify.js +++ b/lib/stringify.js @@ -203,7 +203,8 @@ module.exports = function (object, opts) { )); } + var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; - return prefix + keys.join(delimiter); + return joined.length > 0 ? prefix + joined : ''; }; diff --git a/test/stringify.js b/test/stringify.js index 5d4f68be..537872cb 100644 --- a/test/stringify.js +++ b/test/stringify.js @@ -23,6 +23,11 @@ test('stringify()', function (t) { st.end(); }); + t.test('with query prefix, outputs blank string given an empty object', function (st) { + st.equal(qs.stringify({}, { addQueryPrefix: true }), ''); + st.end(); + }); + t.test('stringifies a nested object', function (st) { st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e');