Skip to content

Commit

Permalink
Merge pull request #196 from mollie/pimm/whatwg-url-api
Browse files Browse the repository at this point in the history
Replace Node.js URL API for WHATWG URL API.
  • Loading branch information
Pimm authored Jan 29, 2021
2 parents 487f2ef + d15f485 commit 9e8cb72
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
3 changes: 2 additions & 1 deletion src/NetworkClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ const camelCase = (() => {
};
})();
/**
* Converts `{ id: 5 }` to `'?id=5'`.
* Returns a stringified version of the passed query to be used as the search portion of a URL. For example:
* `{ id: 5 }` is converted to `'?id=5'` (and `{}` is converted to `''`).
*/
function stringifyQuery(input: Record<string, any>): string {
const entries = getEntries(input);
Expand Down
21 changes: 16 additions & 5 deletions src/resources/Resource.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import { parse as parseUrl } from 'url';
import List from '../data/list/List';
import Maybe from '../types/Maybe';
import TransformingNetworkClient from '../TransformingNetworkClient';

/**
* Returns the parsed search parameters from the passed URL. For example: `'https://example.com?id=5'` is converted to
* `{ id: 5 }` (and `'https://example.com'` is converted to `{}`).
*
* If multiple parameters have the same key (`'https://example.com?id=5&id=6'`), exactly one of them will be
* represented in the returned object.
*/
function parseQueryInUrl(url: string) {
const result: Record<string, string> = {};
new URL(url).searchParams.forEach((value, key) => (result[key] = value));
return result;
}
export default class Resource<R, T extends R> {
constructor(protected readonly networkClient: TransformingNetworkClient<R, T>) {}
/**
Expand All @@ -13,22 +24,22 @@ export default class Resource<R, T extends R> {
let nextPage: Maybe<() => Promise<List<T>>>;
let nextPageCursor: Maybe<string>;
if (links.next != null) {
const { query } = parseUrl(links.next.href, true);
const query = parseQueryInUrl(links.next.href);
nextPage = list.bind(this, {
...selfParameters,
...query,
});
nextPageCursor = query.from as string;
nextPageCursor = query.from;
}
let previousPage: Maybe<() => Promise<List<T>>>;
let previousPageCursor: Maybe<string>;
if (links.previous != null) {
const { query } = parseUrl(links.previous.href, true);
const query = parseQueryInUrl(links.previous.href);
previousPage = list.bind(this, {
...selfParameters,
...query,
});
previousPageCursor = query.from as string;
previousPageCursor = query.from;
}
return Object.assign(input, {
nextPage,
Expand Down

0 comments on commit 9e8cb72

Please sign in to comment.