proxyFetch.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { httpClient } from './httpClient'
  2. import { logger } from './logger'
  3. /**
  4. * 代理增强的fetch函数
  5. * 完全兼容原生fetch API,但自动支持代理
  6. */
  7. export async function proxyFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
  8. const url = typeof input === 'string' ? input : input.toString()
  9. const options = init || {}
  10. try {
  11. const response = await httpClient.request(url, {
  12. method: (options.method as any) || 'GET',
  13. headers: options.headers as Record<string, string>,
  14. body: options.body,
  15. signal: options.signal,
  16. retries: 2, // 默认重试2次
  17. retryDelay: 1000,
  18. })
  19. // 创建兼容的Response对象
  20. const responseInit: ResponseInit = {
  21. status: response.status,
  22. statusText: response.statusText,
  23. headers: response.headers,
  24. }
  25. return new Response(typeof response.data === 'string' ? response.data : JSON.stringify(response.data), responseInit)
  26. } catch (error: any) {
  27. logger.error('ProxyFetch error:', { url, error: error.message })
  28. throw error
  29. }
  30. }
  31. /**
  32. * 全局替换fetch函数 (仅在Node.js环境)
  33. */
  34. export function installProxyFetch(): void {
  35. if (typeof globalThis !== 'undefined') {
  36. // 保存原始fetch
  37. const originalFetch = globalThis.fetch
  38. // 替换为代理版本
  39. ;(globalThis as any).fetch = proxyFetch
  40. // 提供还原方法
  41. ;(globalThis as any).restoreOriginalFetch = () => {
  42. ;(globalThis as any).fetch = originalFetch
  43. }
  44. logger.info('全局fetch已替换为代理版本')
  45. }
  46. }
  47. /**
  48. * 还原原始fetch函数
  49. */
  50. export function restoreOriginalFetch(): void {
  51. if (typeof globalThis !== 'undefined' && (globalThis as any).restoreOriginalFetch) {
  52. ;(globalThis as any).restoreOriginalFetch()
  53. logger.info('已还原原始fetch函数')
  54. }
  55. }