From 768d6b733ca6cbf926a6c713fb168b00720ee1e5 Mon Sep 17 00:00:00 2001 From: Patrick Browne Date: Fri, 6 Dec 2024 13:35:11 +0100 Subject: [PATCH] feat: Configure global undici dispatcher --- src/domain/gitlab-wiki-api.ts | 3 +++ src/pages/api/http-agent.ts | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 src/pages/api/http-agent.ts diff --git a/src/domain/gitlab-wiki-api.ts b/src/domain/gitlab-wiki-api.ts index b668c7a9..05063faa 100644 --- a/src/domain/gitlab-wiki-api.ts +++ b/src/domain/gitlab-wiki-api.ts @@ -5,6 +5,7 @@ import path from "path"; import fs from "fs-extra"; import serverEnv from "src/env/server"; +import { setupUndiciHttpAgent } from "src/pages/api/http-agent"; import { getWikiPage as getStaticWikiPage } from "./gitlab-wiki-static"; @@ -36,6 +37,8 @@ const fetchWithTimeout = async ( ? (id = setTimeout(() => reject(new Error("Timeout")), timeout)) : undefined ); + setupUndiciHttpAgent(); + const fetcher = await fetch(url, options); if (id !== undefined) { clearTimeout(id); diff --git a/src/pages/api/http-agent.ts b/src/pages/api/http-agent.ts new file mode 100644 index 00000000..47bd5c10 --- /dev/null +++ b/src/pages/api/http-agent.ts @@ -0,0 +1,18 @@ +import { ProxyAgent, setGlobalDispatcher } from "undici"; + +declare global { + // eslint-disable-next-line no-var + var __undiciProxyAgent__: ProxyAgent | undefined; +} + +export const setupUndiciHttpAgent = () => { + const HTTP_PROXY = process.env.HTTP_PROXY; + if (!HTTP_PROXY) { + return; + } + if (!globalThis.__undiciProxyAgent__) { + console.log("Setting up undici proxy agent: ", HTTP_PROXY); + globalThis.__undiciProxyAgent__ = new ProxyAgent(HTTP_PROXY); + setGlobalDispatcher(globalThis.__undiciProxyAgent__); + } +};