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 // NOTE(EvanBacon): DO NOT RETURN AN ASYNC WRAPPER. THIS BREAKS LOADING INDICATORS. 13 return (url, init) => { 14 if (typeof url !== 'string') { 15 throw new TypeError('Custom fetch function only accepts a string URL as the first parameter'); 16 } 17 const parsed = new URL(url, baseUrl); 18 if (init?.searchParams) { 19 parsed.search = init.searchParams.toString(); 20 } 21 debug('fetch:', parsed.toString().trim()); 22 return fetch(parsed.toString(), init); 23 }; 24} 25