Skip to content

Commit

Permalink
Require url to be an instance of URL when paginating
Browse files Browse the repository at this point in the history
Fixes #1818
  • Loading branch information
szmarczak committed Aug 4, 2021
1 parent be3462d commit eda69ff
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
4 changes: 4 additions & 0 deletions documentation/4-pagination.md
Expand Up @@ -129,6 +129,10 @@ It should return an object representing Got options pointing to the next page. I
The options are merged automatically with the previous request.\
Therefore the options returned by `pagination.paginate(…)` must reflect changes only.

**Note:**
> - The `url` option (if set) accepts **only** a [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) instance.\
> This prevents `prefixUrl` ambiguity. In order to use a relative URL string, merge it via `new URL(relativeUrl, response.url)`.
#### `filter`

**Type: `Function`**\
Expand Down
2 changes: 1 addition & 1 deletion source/core/options.ts
Expand Up @@ -692,7 +692,7 @@ const defaultInternals: Options['_internals'] = {

if (next) {
return {
url: new URL(next.reference, response.requestUrl),
url: new URL(next.reference, response.url),
};
}

Expand Down
2 changes: 2 additions & 0 deletions source/create.ts
Expand Up @@ -201,6 +201,8 @@ const create = (defaults: InstanceDefaults): Got => {
} else {
normalizedOptions.merge(optionsToMerge);

assert.any([is.urlInstance, is.undefined], optionsToMerge.url);

if (optionsToMerge.url !== undefined) {
normalizedOptions.prefixUrl = '';
normalizedOptions.url = optionsToMerge.url;
Expand Down
16 changes: 15 additions & 1 deletion test/pagination.ts
Expand Up @@ -575,7 +575,7 @@ test('next url in json response', withServer, async (t, server, got) => {
}

return {
url: next,
url: new URL(next),
prefixUrl: '',
searchParams: undefined,
};
Expand Down Expand Up @@ -728,6 +728,20 @@ test('retrieves all elements - relative url', withServer, async (t, server, got)
t.deepEqual(result, [1, 2]);
});

test('throws if url is not an instance of URL', withServer, async (t, server, got) => {
attachHandler(server, 2);

await t.throwsAsync(got.paginate.all<number>('', {
pagination: {
paginate: () => ({
url: 'not an instance of URL',
}),
},
}), {
instanceOf: TypeError,
});
});

test('throws when transform does not return an array', withServer, async (t, server) => {
server.get('/', (_request, response) => {
response.end(JSON.stringify(''));
Expand Down

0 comments on commit eda69ff

Please sign in to comment.