Skip to content

Commit

Permalink
refactor: throw error arrayLimit is exceeded with `throwOnLimitExce…
Browse files Browse the repository at this point in the history
…eded`
  • Loading branch information
IamLizu committed Nov 12, 2024
1 parent 33c4c7f commit b5e89b7
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
11 changes: 9 additions & 2 deletions lib/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,16 @@ var interpretNumericEntities = function (str) {
});
};

var parseArrayValue = function (val, options) {
var parseArrayValue = function (val, options, currentArrayLength) {
if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {
return val.split(',');
}

// Check if array length exceeds the limit before adding new values
if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) {
throw new Error('Array limit exceeded. Only ' + options.arrayLimit + ' elements allowed in an array.');
}

return val;
};

Expand Down Expand Up @@ -104,8 +109,10 @@ var parseValues = function parseQueryStringValues(str, options) {
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');

const currentArrayLength = isArray(obj[key]) ? obj[key].length : 0;
val = utils.maybeMap(
parseArrayValue(part.slice(pos + 1), options),
parseArrayValue(part.slice(pos + 1), options, currentArrayLength),
function (encodedVal) {
return options.decoder(encodedVal, defaults.decoder, charset, 'value');
}
Expand Down
33 changes: 32 additions & 1 deletion test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -1084,8 +1084,39 @@ test('parse()', function (t) {

st.end();
});


t.test('array limit tests', function (st) {
st.test('does not throw error when array is within limit', function (sst) {
const result = qs.parse('a[]=1&a[]=2&a[]=3', { arrayLimit: 5, throwOnLimitExceeded: true });
sst.deepEqual(result, { a: ['1', '2', '3'] }, 'Should parse array without errors');
sst.end();
});

st.test('throws error when throwOnLimitExceeded is present but not boolean for array limit', function (sst) {
sst.throws(
function () {
qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3, throwOnLimitExceeded: "true" });
},
new TypeError('`throwOnLimitExceeded` option must be a boolean'),
'Should throw error when throwOnLimitExceeded is present and not boolean for array limit'
);
sst.end();
});

st.test('throws error when array limit exceeded', function (sst) {
sst.throws(
function () {
qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3, throwOnLimitExceeded: true });
},
new Error('Array limit exceeded. Only 3 elements allowed in an array.'),
'Should throw error when array limit is exceeded'
);
sst.end();
});

st.end();
});

t.end();
});

Expand Down

0 comments on commit b5e89b7

Please sign in to comment.