stock-bot/libs/http-client/src/proxy-manager.ts
2025-06-04 16:37:28 -04:00

39 lines
1.1 KiB
TypeScript

import { HttpsProxyAgent } from 'https-proxy-agent';
import { SocksProxyAgent } from 'socks-proxy-agent';
import type { ProxyConfig } from './types.js';
import { validateProxyConfig } from './types.js';
export class ProxyManager {
/**
* Create appropriate proxy agent based on configuration
*/
static createAgent(proxy: ProxyConfig): HttpsProxyAgent<string> | SocksProxyAgent {
const { type, host, port, username, password } = proxy;
let proxyUrl: string;
if (username && password) {
proxyUrl = `${type}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}`;
} else {
proxyUrl = `${type}://${host}:${port}`;
}
switch (type) {
case 'http':
case 'https':
return new HttpsProxyAgent(proxyUrl);
case 'socks4':
case 'socks5':
return new SocksProxyAgent(proxyUrl);
default:
throw new Error(`Unsupported proxy type: ${type}`);
}
}
/**
* Validate proxy configuration
*/
static validateConfig(proxy: ProxyConfig): void {
// Use the centralized validation function
validateProxyConfig(proxy);
}
}