File size: 951 Bytes
0133533
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { HttpsProxyAgent } from 'https-proxy-agent'
import { getProxyUrl } from '../configs/config.js'

let cachedAgent = null
let cachedProxyUrl = null

export function getNextProxyAgent(targetUrl) {
  const proxyUrl = getProxyUrl()

  // 如果没有配置代理,返回 null(直连)
  if (!proxyUrl) {
    return null
  }

  // 如果代理 URL 改变,清除缓存
  if (proxyUrl !== cachedProxyUrl) {
    cachedAgent = null
    cachedProxyUrl = proxyUrl
  }

  // 如果已有缓存的代理,直接返回
  if (cachedAgent) {
    return { agent: cachedAgent, proxy: { url: proxyUrl } }
  }

  // 创建新的代理
  try {
    cachedAgent = new HttpsProxyAgent(proxyUrl)
    console.log(`使用代理 ${proxyUrl} 请求 ${targetUrl}`)
    return { agent: cachedAgent, proxy: { url: proxyUrl } }
  } catch (error) {
    console.error(`为 ${proxyUrl} 创建代理失败:`, error)
    return null
  }
}