(url: string, options: any = {}, timeout = 60)
| 9 | * @returns |
| 10 | */ |
| 11 | export async function proxyFetch(url: string, options: any = {}, timeout = 60) { |
| 12 | const { systemProxy } = await getSystemProxy(); |
| 13 | console.log(systemProxy.http_proxy, options); |
| 14 | const agentOptions = { |
| 15 | secureProtocol: 'TLSv1_2_method', |
| 16 | }; |
| 17 | const controller = new AbortController(); |
| 18 | const { signal } = controller; |
| 19 | |
| 20 | // set timeout |
| 21 | const timeoutId = setTimeout(() => controller.abort(), timeout * 1000); |
| 22 | try { |
| 23 | const response: Response = await fetch(url, { |
| 24 | ...options, |
| 25 | method: options.method || "GET", |
| 26 | headers: { |
| 27 | ...options.headers, |
| 28 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3', |
| 29 | }, |
| 30 | signal, |
| 31 | agent: systemProxy.http_proxy ? new HttpsProxyAgent(systemProxy.http_proxy as string, agentOptions) : undefined, |
| 32 | }); |
| 33 | |
| 34 | if (!response.ok) { |
| 35 | throw new Error(`Failed to fetch from ${url}. Status: ${response.status} ${response.statusText}`); |
| 36 | } |
| 37 | |
| 38 | return response |
| 39 | } catch(err: any) { |
| 40 | if (err.name === 'AbortError') { |
| 41 | throw new Error('Request timed out'); |
| 42 | } |
| 43 | throw err; |
| 44 | } finally { |
| 45 | clearTimeout(timeoutId); |
| 46 | } |
| 47 | } |
| 48 |
no test coverage detected