Skip to content

Commit

Permalink
Make the query values more strict (#698)
Browse files Browse the repository at this point in the history
  • Loading branch information
szmarczak authored and sindresorhus committed Jan 17, 2019
1 parent bf86d58 commit 5376216
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
5 changes: 5 additions & 0 deletions source/normalize-arguments.js
Expand Up @@ -6,6 +6,7 @@ const urlParseLax = require('url-parse-lax');
const lowercaseKeys = require('lowercase-keys');
const urlToOptions = require('./utils/url-to-options');
const isFormData = require('./utils/is-form-data');
const validateSearchParams = require('./utils/validate-search-params');
const merge = require('./merge');
const knownHookEvents = require('./known-hook-events');

Expand Down Expand Up @@ -152,6 +153,10 @@ const normalize = (url, options, defaults) => {
const {query} = options;
if (is.nonEmptyString(query) || is.nonEmptyObject(query) || query instanceof URLSearchParams) {
if (!is.string(query)) {
if (!(query instanceof URLSearchParams)) {
validateSearchParams(query);
}

options.query = (new URLSearchParams(query)).toString();
}

Expand Down
15 changes: 15 additions & 0 deletions source/utils/validate-search-params.js
@@ -0,0 +1,15 @@
'use strict';
const is = require('@sindresorhus/is');

module.exports = query => {
const verify = (value, type) => {
if (!is.string(value) && !is.number(value) && !is.boolean(value) && !is.null(value)) {
throw new TypeError(`The query ${type} '${value}' must be a string, number, boolean or null`);
}
};

for (const [key, value] of Object.entries(query)) {
verify(key, 'key');
verify(value, 'value');
}
};
16 changes: 16 additions & 0 deletions test/arguments.js
Expand Up @@ -223,3 +223,19 @@ test('throws when trying to modify baseUrl after options got normalized', async

await t.throwsAsync(instanceA('/'), 'Failed to set baseUrl. Options are normalized already.');
});

test('throws if the query key is invalid', async t => {
await t.throwsAsync(() => got(s.url, {
query: {
[[]]: []
}
}), TypeError);
});

test('throws if the query value is invalid', async t => {
await t.throwsAsync(() => got(s.url, {
query: {
foo: []
}
}), TypeError);
});

0 comments on commit 5376216

Please sign in to comment.