-
-
Save BOTKooper/e7964f5aca05d01756ddc1b152903ed4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Proxy } from "../types"; | |
import * as undici from "undici"; | |
export const fetchWithProxy = ( | |
proxy: Proxy | undefined | null, | |
url: string, | |
opts: Parameters<typeof fetch>[1] | |
): Promise<Response> => { | |
if (!proxy) { | |
return fetch(url, opts); | |
} | |
let proxyStr = `${proxy.username}:${proxy.password}@${proxy.host}:${proxy.port}`; | |
const prefix = | |
proxy.type === "HTTPS" | |
? "https://" | |
: proxy.type === "HTTP" | |
? "http://" | |
: "socks5://"; | |
if (globalThis.Bun !== undefined) { | |
return fetch(url, { | |
...opts, | |
proxy: `${prefix}${proxyStr}`, | |
} as any); | |
} | |
const agent = new undici.ProxyAgent({ | |
uri: `${prefix}${proxyStr}`, | |
token: `Basic ${Buffer.from(`${proxy.username}:${proxy.password}`).toString( | |
"base64" | |
)}`, | |
}); | |
return undici.fetch(url, { | |
...opts, | |
dispatcher: agent, | |
} as any) as any; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment