Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for relative URLs and searchParams even in non-browsers #271

Merged
merged 2 commits into from
Jul 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,8 +272,8 @@ class Ky {
this.request = new globals.Request(this._input, this._options);

if (this._options.searchParams) {
const url = new URL(this.request.url);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry I'm late to the party. Does this change anything? this.request.url is an absolute URL anyway... I'm just asking because I don't like RegExps.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like regex either. this.request.url can be a relative URL in some environments, e.g. Node and Deno.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then why not this?

const requestUrl = this.request.url;
const searchIndex = requestUrl.indexOf('?');
const urlWithoutParameters = searchIndex === -1 ? requestUrl : requestUrl.slice(0, searchIndex);
const url = `${urlWithoutParameters}${searchParams.toString()}`;

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe your code would remove the hash fragment from a URL, unlike the new URL() code we had before.

Granted, the hash fragment shouldn't be sent to the server anyway, so that shouldn't really matter. But I figure we should be spec compliant and unobtrusive by only modifying the search params and nothing more. It's possible that a custom fetch function might care about the hash fragment, for example.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm... Fair point. We could also indexOf('#') but that would add more complexity. The regex solution is much clearer.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, my thoughts exactly. I did add tests that assert we don't modify the hash fragment. So if someone comes up with a clean non-regex solution, go ahead and give it a shot. It'll be checked thoroughly by the tests.

url.search = new URLSearchParams(this._options.searchParams);
const searchParams = '?' + new URLSearchParams(this._options.searchParams).toString();
const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved

// To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one
if (((supportsFormData && this._options.body instanceof globals.FormData) || this._options.body instanceof URLSearchParams) && !(this._options.headers && this._options.headers['content-type'])) {
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@
"form-data": "^3.0.0",
"node-fetch": "^2.5.0",
"nyc": "^15.0.0",
"puppeteer": "^3.0.4",
"puppeteer": "^5.1.0",
"rollup": "^2.10.2",
"tsd": "^0.11.0",
"tsd": "^0.13.1",
"xo": "^0.25.3"
},
"sideEffects": false,
Expand Down
53 changes: 30 additions & 23 deletions test/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const pBody = util.promisify(body);

test('prefixUrl option', withPage, async (t, page) => {
const server = await createTestServer();

server.get('/', (request, response) => {
response.end('zebra');
});
Expand All @@ -19,21 +20,23 @@ test('prefixUrl option', withPage, async (t, page) => {
await page.goto(server.url);
await page.addScriptTag({path: './umd.js'});

await t.throwsAsync(async () => {
return page.evaluate(() => {
await t.throwsAsync(
page.evaluate(() => {
return window.ky('/foo', {prefixUrl: '/'});
});
}, {message: /`input` must not begin with a slash when using `prefixUrl`/});

const unprefixed = await page.evaluate(url => {
return window.ky(`${url}/api/unicorn`).text();
}),
{message: /`input` must not begin with a slash when using `prefixUrl`/}
);

const results = await page.evaluate(url => {
return Promise.all([
window.ky(`${url}/api/unicorn`).text(),
window.ky(`${url}/api/unicorn`, {prefixUrl: null}).text(),
window.ky('api/unicorn', {prefixUrl: url}).text(),
window.ky('api/unicorn', {prefixUrl: `${url}/`}).text()
]);
}, server.url);
t.is(unprefixed, 'rainbow');

const prefixed = await page.evaluate(prefixUrl => {
return window.ky('api/unicorn', {prefixUrl}).text();
}, server.url);
t.is(prefixed, 'rainbow');
t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow']);

await server.close();
});
Expand Down Expand Up @@ -96,7 +99,7 @@ test('onDownloadProgress works', withPage, async (t, page) => {

server.get('/', (request, response) => {
response.writeHead(200, {
'content-length': 4
'content-length': '4'
});

response.write('me');
Expand Down Expand Up @@ -289,6 +292,8 @@ test('headers are preserved when input is a Request and there are searchParams i
});

test('retry with body', withPage, async (t, page) => {
t.plan(4);

let requestCount = 0;

const server = await createTestServer();
Expand All @@ -297,22 +302,24 @@ test('retry with body', withPage, async (t, page) => {
});
server.put('/test', async (request, response) => {
requestCount++;
await pBody(request);
t.is(await pBody(request), 'foo');
response.sendStatus(502);
});

await page.goto(server.url);
await page.addScriptTag({path: './umd.js'});

const error = await page.evaluate(url => {
const request = window.ky(url + '/test', {
body: 'foo',
method: 'PUT',
retry: 2
}).text();
return request.catch(error_ => error_.toString());
}, server.url);
t.is(error, 'HTTPError: Bad Gateway');
await t.throwsAsync(
page.evaluate(async url => {
return window.ky(url + '/test', {
body: 'foo',
method: 'PUT',
retry: 2
});
}, server.url),
{message: /HTTPError: Bad Gateway/}
);

t.is(requestCount, 2);

await server.close();
Expand Down
18 changes: 18 additions & 0 deletions test/fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import test from 'ava';
import ky from '..';

test.serial('relative URLs are passed to fetch unresolved', async t => {
const originalFetch = global.fetch;
global.fetch = async input => {
t.true(input.url.startsWith('/'));
return new Response(input.url);
};

t.is(await ky('/unicorn').text(), '/unicorn');
t.is(await ky('/unicorn', {searchParams: {foo: 'bar'}}).text(), '/unicorn?foo=bar');
t.is(await ky('/unicorn#hash', {searchParams: 'foo'}).text(), '/unicorn?foo=#hash');
t.is(await ky('/unicorn?old', {searchParams: 'new'}).text(), '/unicorn?new=');
t.is(await ky('/unicorn?old#hash', {searchParams: 'new'}).text(), '/unicorn?new=#hash');
t.is(await ky('unicorn', {prefixUrl: '/api/'}).text(), '/api/unicorn');
global.fetch = originalFetch;
});
1 change: 0 additions & 1 deletion test/helpers/with-page.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ export default async function withPage(t, run) {
try {
await run(t, page);
} finally {
await page.close();
await browser.close();
}
}