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 { AxiosInstance, default as axios_ } from 'axios'
|
||||||
|
import { ProxyAgent } from 'proxy-agent'
|
||||||
|
|
||||||
import { proxyManager } from './ProxyManager'
|
import { proxyManager } from './ProxyManager'
|
||||||
|
|
||||||
class AxiosProxy {
|
class AxiosProxy {
|
||||||
private cacheAxios: AxiosInstance | undefined
|
private cacheAxios: AxiosInstance | null = null
|
||||||
private proxyURL: string | undefined
|
private proxyAgent: ProxyAgent | null = null
|
||||||
|
|
||||||
get axios(): AxiosInstance {
|
get axios(): AxiosInstance {
|
||||||
const currentProxyURL = proxyManager.getProxyUrl()
|
const currentProxyAgent = proxyManager.getProxyAgent()
|
||||||
if (this.proxyURL !== currentProxyURL) {
|
|
||||||
this.proxyURL = currentProxyURL
|
// 如果代理发生变化或尚未初始化,则重新创建 axios 实例
|
||||||
const agent = proxyManager.getProxyAgent()
|
if (this.cacheAxios === null || (currentProxyAgent !== null && this.proxyAgent !== currentProxyAgent)) {
|
||||||
|
this.proxyAgent = currentProxyAgent
|
||||||
|
|
||||||
|
// 创建带有代理配置的 axios 实例
|
||||||
this.cacheAxios = axios_.create({
|
this.cacheAxios = axios_.create({
|
||||||
proxy: false,
|
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
|
return this.cacheAxios
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user