import { httpClient } from './httpClient' import { logger } from './logger' /** * 代理增强的fetch函数 * 完全兼容原生fetch API,但自动支持代理 */ export async function proxyFetch(input: RequestInfo | URL, init?: RequestInit): Promise { const url = typeof input === 'string' ? input : input.toString() const options = init || {} try { const response = await httpClient.request(url, { method: (options.method as any) || 'GET', headers: options.headers as Record, body: options.body, signal: options.signal, retries: 2, // 默认重试2次 retryDelay: 1000, }) // 创建兼容的Response对象 const responseInit: ResponseInit = { status: response.status, statusText: response.statusText, headers: response.headers, } return new Response(typeof response.data === 'string' ? response.data : JSON.stringify(response.data), responseInit) } catch (error: any) { logger.error('ProxyFetch error:', { url, error: error.message }) throw error } } /** * 全局替换fetch函数 (仅在Node.js环境) */ export function installProxyFetch(): void { if (typeof globalThis !== 'undefined') { // 保存原始fetch const originalFetch = globalThis.fetch // 替换为代理版本 ;(globalThis as any).fetch = proxyFetch // 提供还原方法 ;(globalThis as any).restoreOriginalFetch = () => { ;(globalThis as any).fetch = originalFetch } logger.info('全局fetch已替换为代理版本') } } /** * 还原原始fetch函数 */ export function restoreOriginalFetch(): void { if (typeof globalThis !== 'undefined' && (globalThis as any).restoreOriginalFetch) { ;(globalThis as any).restoreOriginalFetch() logger.info('已还原原始fetch函数') } }