import { conf } from "@/setup/config"; import { ofetch } from "ofetch"; let proxyUrlIndex = Math.floor(Math.random() * conf().PROXY_URLS.length); // round robins all proxy urls function getProxyUrl(): string { const url = conf().PROXY_URLS[proxyUrlIndex]; proxyUrlIndex = (proxyUrlIndex + 1) % conf().PROXY_URLS.length; return url; } type P = Parameters>; type R = ReturnType>; const baseFetch = ofetch.create({ retry: 0, }); export function makeUrl(url: string, data: Record) { let parsedUrl: string = url; Object.entries(data).forEach(([k, v]) => { parsedUrl = parsedUrl.replace(`{${k}}`, encodeURIComponent(v)); }); return parsedUrl; } export function mwFetch(url: string, ops: P[1] = {}): R { return baseFetch(url, ops); } export function proxiedFetch(url: string, ops: P[1] = {}): R { let combinedUrl = ops?.baseURL ?? ""; if ( combinedUrl.length > 0 && combinedUrl.endsWith("/") && url.startsWith("/") ) combinedUrl += url.slice(1); else if ( combinedUrl.length > 0 && !combinedUrl.endsWith("/") && !url.startsWith("/") ) combinedUrl += `/${url}`; else combinedUrl += url; const parsedUrl = new URL(combinedUrl); Object.entries(ops?.params ?? {}).forEach(([k, v]) => { parsedUrl.searchParams.set(k, v); }); return baseFetch(getProxyUrl(), { ...ops, baseURL: undefined, params: { destination: parsedUrl.toString(), }, }); }