1import { URL } from 'url';
2
3import { FetchLike } from './client.types';
4
5/**
6 * Wrap a fetch function with support for a predefined base URL.
7 * This implementation works like the browser fetch, applying the input to a prefix base URL.
8 */
9export function wrapFetchWithBaseUrl(fetch: FetchLike, baseUrl: string): FetchLike {
10  return (url, init) => {
11    if (typeof url !== 'string') {
12      throw new TypeError('Custom fetch function only accepts a string URL as the first parameter');
13    }
14    const parsed = new URL(url, baseUrl);
15    if (init?.searchParams) {
16      parsed.search = init.searchParams.toString();
17    }
18    return fetch(parsed.toString(), init);
19  };
20}
21