Skip to content

Instantly share code, notes, and snippets.

@BOTKooper
Last active May 8, 2024 22:07
Show Gist options
  • Save BOTKooper/e7964f5aca05d01756ddc1b152903ed4 to your computer and use it in GitHub Desktop.
Save BOTKooper/e7964f5aca05d01756ddc1b152903ed4 to your computer and use it in GitHub Desktop.
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