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.
This commit is contained in:
parent
4789ba3e8f
commit
49a7b2dc8b
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user