diff --git a/src/utils/Fetcher.ts b/src/utils/Fetcher.ts index 77be3a1..17f35ef 100644 --- a/src/utils/Fetcher.ts +++ b/src/utils/Fetcher.ts @@ -8,7 +8,7 @@ import winston from 'winston'; import { BlockedError, HttpError, NotFoundError, QueueIsFullError, TimeoutError, TooManyRequestsError, TooManyTimeoutsError } from '../error'; import { BlockedReason, Context } from '../types'; import { noCache } from './config'; -import { createProxyAgent, getProxyForUrl } from './dispatcher'; +import { getProxyAgent, getProxyForUrl } from './dispatcher'; import { envGet } from './env'; interface HttpCacheItem { @@ -288,7 +288,7 @@ export class Fetcher { ...init, keepalive: true, signal: AbortSignal.timeout(init?.timeout ?? this.DEFAULT_TIMEOUT), - ...(/* istanbul ignore next */ proxyUrl && { dispatcher: createProxyAgent(proxyUrl) }), + ...(/* istanbul ignore next */ proxyUrl && { dispatcher: getProxyAgent(proxyUrl) }), }; response = await fetch(finalUrl, finalInit); diff --git a/src/utils/dispatcher.ts b/src/utils/dispatcher.ts index 8e05c77..fe877f5 100644 --- a/src/utils/dispatcher.ts +++ b/src/utils/dispatcher.ts @@ -24,10 +24,17 @@ export const getProxyForUrl = (ctx: Context, url: URL): URL | undefined => { return undefined; }; -export const createProxyAgent = (proxyUrl: URL): Dispatcher => { - if (proxyUrl.protocol === 'socks5:') { - return socksDispatcher({ type: 5, host: proxyUrl.hostname, port: parseInt(proxyUrl.port) }); +const proxyAgents = new Map(); +export const getProxyAgent = (proxyUrl: URL): Dispatcher => { + let proxyAgent = proxyAgents.get(proxyUrl.href); + + if (!proxyAgent) { + proxyAgent = proxyUrl.protocol === 'socks5:' + ? socksDispatcher({ type: 5, host: proxyUrl.hostname, port: parseInt(proxyUrl.port) }) + : new ProxyAgent({ uri: proxyUrl.href }); + + proxyAgents.set(proxyUrl.href, proxyAgent); } - return new ProxyAgent({ uri: proxyUrl.href }); + return proxyAgent; };