Skip to content

Commit 9d137ff

Browse files
deepview-autofixclaudeChALkeR
authored
fix: skip empty array values in stringify
Empty array values caused malformed query strings with leading or trailing `&` separators because the separator was appended unconditionally for every key while the inner loop produced no output. For example, `stringify({a: [], b: "1"})` produced `"&b=1"` and `stringify({a: "1", b: []})` produced `"a=1&"`. Skip empty arrays entirely and only emit the separator when the current key actually contributes a key=value pair, matching the behavior of the native `querystring` module. Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: DeepView Autofix <276251120+deepview-autofix@users.noreply.github.com> Co-Authored-By: Nikita Skovoroda <chalkerx@gmail.com> Signed-off-by: Nikita Skovoroda <chalkerx@gmail.com>
1 parent 9dcbaf2 commit 9d137ff

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

lib/stringify.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,14 @@ function stringify(input) {
3939
const value = input[key];
4040
const encodedKey = encodeString(key) + "=";
4141

42-
if (i) {
43-
result += separator;
44-
}
45-
4642
if (Array.isArray(value)) {
4743
valueLength = value.length;
44+
if (valueLength === 0) {
45+
continue;
46+
}
47+
if (result.length > 0) {
48+
result += separator;
49+
}
4850
for (let j = 0; j < valueLength; j++) {
4951
if (j) {
5052
result += separator;
@@ -56,6 +58,9 @@ function stringify(input) {
5658
result += getAsPrimitive(value[j]);
5759
}
5860
} else {
61+
if (result.length > 0) {
62+
result += separator;
63+
}
5964
result += encodedKey;
6065
result += getAsPrimitive(value);
6166
}

test/stringify.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,13 @@ test("should coerce numbers to string", () => {
9797
assert.strictEqual(qs.stringify({ foo: Number.POSITIVE_INFINITY }), "foo=");
9898
});
9999

100+
test("should skip empty array values without leaving stray separators", () => {
101+
assert.strictEqual(qs.stringify({ a: [], b: "1" }), "b=1");
102+
assert.strictEqual(qs.stringify({ a: "1", b: [] }), "a=1");
103+
assert.strictEqual(qs.stringify({ a: "1", b: [], c: "2" }), "a=1&c=2");
104+
assert.strictEqual(qs.stringify({ a: [] }), "");
105+
});
106+
100107
test("should return empty string on certain inputs", () => {
101108
assert.strictEqual(qs.stringify(undefined as never), "");
102109
assert.strictEqual(qs.stringify(0 as never), "");

0 commit comments

Comments
 (0)