From 49a7b2dc8be25afbb6b1757f7f45973dd972ab9d Mon Sep 17 00:00:00 2001 From: beyondkmp Date: Mon, 21 Apr 2025 09:20:44 +0800 Subject: [PATCH] refactor(AxiosProxy): improve proxy handling and initialization logic - Changed cacheAxios from undefined to null for better initialization. - Updated proxy handling to use ProxyAgent, ensuring axios instance is recreated when the proxy changes. - Simplified axios instance creation by directly using the current proxy agent. --- src/main/services/AxiosProxy.ts | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/main/services/AxiosProxy.ts b/src/main/services/AxiosProxy.ts index bdac92bd..6f767bd3 100644 --- a/src/main/services/AxiosProxy.ts +++ b/src/main/services/AxiosProxy.ts @@ -1,25 +1,27 @@ import { AxiosInstance, default as axios_ } from 'axios' +import { ProxyAgent } from 'proxy-agent' import { proxyManager } from './ProxyManager' class AxiosProxy { - private cacheAxios: AxiosInstance | undefined - private proxyURL: string | undefined + private cacheAxios: AxiosInstance | null = null + private proxyAgent: ProxyAgent | null = null get axios(): AxiosInstance { - const currentProxyURL = proxyManager.getProxyUrl() - if (this.proxyURL !== currentProxyURL) { - this.proxyURL = currentProxyURL - const agent = proxyManager.getProxyAgent() + const currentProxyAgent = proxyManager.getProxyAgent() + + // 如果代理发生变化或尚未初始化,则重新创建 axios 实例 + if (this.cacheAxios === null || (currentProxyAgent !== null && this.proxyAgent !== currentProxyAgent)) { + this.proxyAgent = currentProxyAgent + + // 创建带有代理配置的 axios 实例 this.cacheAxios = axios_.create({ proxy: false, - ...(agent && { httpAgent: agent, httpsAgent: agent }) + httpAgent: currentProxyAgent || undefined, + httpsAgent: currentProxyAgent || undefined }) } - if (this.cacheAxios === undefined) { - this.cacheAxios = axios_.create({ proxy: false }) - } return this.cacheAxios } }