Skip to content

Commit

Permalink
Allow the query option to be a URLSearchParams instance (#565)
Browse files Browse the repository at this point in the history
Fixes #554
  • Loading branch information
lorenzofox3 authored and szmarczak committed Aug 23, 2018
1 parent 97533e5 commit b8a086f
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 10 deletions.
2 changes: 1 addition & 1 deletion readme.md
Expand Up @@ -183,7 +183,7 @@ Parse response body with `JSON.parse` and set `accept` header to `application/js

###### query

Type: `string` `Object`<br>
Type: `string` `Object` [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)<br>

Query string object that will be added to the request URL. This will override the query string in `url`.

Expand Down
11 changes: 4 additions & 7 deletions source/normalize-arguments.js
Expand Up @@ -68,16 +68,13 @@ module.exports = (url, options, defaults) => {
}

const {query} = options;
if (!is.empty(query)) {
if (!is.string(query)) {
options.query = (new URLSearchParamsGlobal(query)).toString();
}

options.path = `${options.path.split('?')[0]}?${options.query}`;
if (!is.empty(query) || query instanceof URLSearchParamsGlobal) {
const queryParams = new URLSearchParamsGlobal(query);
options.path = `${options.path.split('?')[0]}?${queryParams.toString()}`;
delete options.query;
}

delete options.query;

if (options.json && is.undefined(options.headers.accept)) {
options.headers.accept = 'application/json';
}
Expand Down
8 changes: 7 additions & 1 deletion test/arguments.js
@@ -1,4 +1,4 @@
import {URL} from 'url';
import {URL, URLSearchParams} from 'url';
import test from 'ava';
import pEvent from 'p-event';
import got from '../source';
Expand Down Expand Up @@ -99,6 +99,12 @@ test('overrides querystring from opts', async t => {
t.is(response.body, '/?test=wow');
});

test('the `query` option can be a URLSearchParams', async t => {
const query = new URLSearchParams({test: 'wow'});
const {body} = await got(s.url, {query});
t.is(body, '/?test=wow');
});

test('should ignore empty query object', async t => {
t.is((await got(`${s.url}/test`, {query: {}})).requestUrl, `${s.url}/test`);
});
Expand Down
2 changes: 1 addition & 1 deletion test/redirects.js
Expand Up @@ -82,7 +82,7 @@ test.before('setup', async () => {
response.end();
});

http.on('/relativeQuery?bang', (request, response) => {
http.on('/relativeQuery?bang=', (request, response) => {
response.writeHead(302, {
location: '/'
});
Expand Down

0 comments on commit b8a086f

Please sign in to comment.