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