Skip to content

Commit

Permalink
[Fix] stringify: with comma:true and RFC3986 format, decode comma…
Browse files Browse the repository at this point in the history
… for an array as a reserved char
  • Loading branch information
Mohamed Omar authored and ljharb committed Oct 18, 2019
1 parent 6151be3 commit 8da95de
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
17 changes: 15 additions & 2 deletions lib/stringify.js
Expand Up @@ -74,8 +74,6 @@ var stringify = function stringify(
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate(obj);
} else if (generateArrayPrefix === 'comma' && isArray(obj)) {
obj = obj.join(',');
}

if (obj === null) {
Expand All @@ -94,6 +92,21 @@ var stringify = function stringify(
return [formatter(prefix) + '=' + formatter(String(obj))];
}

if (generateArrayPrefix === 'comma' && isArray(obj)) {
if (formatter !== formats.formatters['RFC3986']) {
obj = obj.join(',');
} else {
if (encoder) {
var commaKey = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key');
var commaValue = obj.map(function (item) {
return formatter(encoder(item, defaults.encoder, charset, 'value'));
});
return [formatter(commaKey) + '=' + commaValue];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
}

var values = [];

if (typeof obj === 'undefined') {
Expand Down
16 changes: 14 additions & 2 deletions test/stringify.js
Expand Up @@ -105,7 +105,17 @@ test('stringify()', function (t) {
);
st.equal(
qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' }),
'a=b%2Cc%2Cd',
'a=b,c,d',
'comma => comma'
);
st.equal(
qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma', format: 'RFC3986' }),
'a=b,c,d',
'comma => comma'
);
st.equal(
qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma', format: 'RFC1738' }),
'a=b%2cc%2cd',
'comma => comma'
);
st.equal(
Expand Down Expand Up @@ -134,7 +144,9 @@ test('stringify()', function (t) {
t.test('stringifies a nested array value', function (st) {
st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'indices' }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d');
st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'brackets' }), 'a%5Bb%5D%5B%5D=c&a%5Bb%5D%5B%5D=d');
st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'comma' }), 'a%5Bb%5D=c%2Cd'); // a[b]=c,d
st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'comma' }), 'a%5Bb%5D=c,d'); // a[b]=c,d
st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'comma', format: 'RFC3986' }), 'a%5Bb%5D=c,d'); // a[b]=c,d
st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'comma', format: 'RFC1738' }), 'a%5Bb%5D=c%2cd'); // a[b]=c,d
st.equal(qs.stringify({ a: { b: ['c', 'd'] } }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d');
st.end();
});
Expand Down

0 comments on commit 8da95de

Please sign in to comment.