Skip to content

Commit

Permalink
WIP: Add array item index when building querystring (for complex obje…
Browse files Browse the repository at this point in the history
…cts) #400
  • Loading branch information
tomas committed Apr 7, 2022
1 parent 8353cdb commit 730ca57
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/querystring.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function stringifyArray(arr, prefix) {

for (var i = 0, len = arr.length; i < len; i++) {
if (prefix)
ret.push(stringify(arr[i], prefix + '[]'));
ret.push(stringify(arr[i], prefix + '[' + i + ']'));
else
ret.push(stringify(arr[i]));
}
Expand Down
41 changes: 39 additions & 2 deletions test/querystring_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ describe('stringify', function() {

it('works', function() {
var res = stringify({ foo: ['bar', 'baz'] });
res.should.eql('foo[]=bar&foo[]=baz');
res.should.eql('foo[0]=bar&foo[1]=baz');
})

})
Expand All @@ -118,11 +118,48 @@ describe('stringify', function() {

it('works', function() {
var res = stringify({ foo: [{'1': 'bar'}, {'2': 'baz'}] });
res.should.eql('foo[][1]=bar&foo[][2]=baz');
res.should.eql('foo[0][1]=bar&foo[1][2]=baz');
})

})

})

describe('with a complex object', function() {

var data = {
field1: 'x',
field3: [
{
subfield1: 'this is a string',
subfield2: ['this is array'],
subfield3: ['another array']
},
{
subfield1: 'this is a string',
subfield2: ['this is array'],
subfield3: ['another array']
},
{
subfield1: 'this is a string',
subfield2: ['this is array'],
subfield3: ['another array']
},
]
};

// TODO
it('works as expected', function() {
var encoded = stringify(data)
encoded.should.eql('field1=x&field3[0][subfield1]=this%20is%20a%20string&field3[0][subfield2][0]=this%20is%20array&field3[0][subfield3][0]=another%20array&field3[1][subfield1]=this%20is%20a%20string&field3[1][subfield2][0]=this%20is%20array&field3[1][subfield3][0]=another%20array&field3[2][subfield1]=this%20is%20a%20string&field3[2][subfield2][0]=this%20is%20array&field3[2][subfield3][0]=another%20array')

// console.log(data);
// console.log(encoded.replace(/\&/g, '\n'));

// var qs = require("querystring");
// var res = qs.decode(encoded);
// console.log(res);
})
})

})

0 comments on commit 730ca57

Please sign in to comment.