import fp from "fastify-plugin"; import proxyPlugin from "@fastify/http-proxy"; import { logProxy } from "./logger.js"; import type { ProxyItem } from "./config.js"; const createProxy = (server: any, silent: boolean, httpProxy?: string) => ({ from, to, opts }: ProxyItem): void => { if (!silent) logProxy(from, to); const prefix = from.endsWith("/") ? from.slice(0, -1) : from; const url = new URL(to); const upstream = url.origin; const rewritePrefix = url.pathname; server.register(proxyPlugin, { prefix, upstream, rewritePrefix, undici: httpProxy ? { proxy: httpProxy } : false, ...opts, }); }; export default fp( async ( server: any, { proxy = [], silent = false, httpProxy, }: { proxy?: ProxyItem[]; silent?: boolean; httpProxy?: string }, ) => proxy.forEach(createProxy(server, silent, httpProxy)), );