Last active
June 15, 2024 07:50
-
-
Save unnoq/3c1448d39f4c03d93e935f02efec8be4 to your computer and use it in GitHub Desktop.
better-fetch
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 { honoRouter } from '@api-node/lib/hono'; | |
import { zValidator } from '@hono/zod-validator'; | |
import { Dispatcher, ProxyAgent } from 'undici'; | |
import { z } from 'zod'; | |
export const betterFetchRouter = honoRouter.all( | |
'/', | |
zValidator( | |
'header', | |
z.object({ | |
'x-fastfn-better-fetch-url': z.string().url(), | |
'x-fastfn-better-fetch-proxy': z.string().url().optional(), | |
}) | |
), | |
async (c) => { | |
const headerData = c.req.valid('header'); | |
const dispatcher = headerData['x-fastfn-better-fetch-proxy'] | |
? (new ProxyAgent({ | |
uri: headerData['x-fastfn-better-fetch-proxy'], | |
requestTls: { rejectUnauthorized: false }, | |
}) as Dispatcher) | |
: undefined; | |
const res = await fetch(headerData['x-fastfn-better-fetch-url'], { | |
dispatcher, | |
method: c.req.raw.method, | |
headers: cloneAndCleanHeaders(c.req.raw.headers), | |
body: c.req.raw.body, | |
signal: c.req.raw.signal, | |
redirect: c.req.raw.redirect, | |
}); | |
const newHeaders = new Headers(res.headers); | |
newHeaders.delete('content-encoding'); | |
return new Response(res.body, { | |
status: res.status, | |
headers: newHeaders, | |
statusText: res.statusText, | |
}); | |
} | |
); | |
function cloneAndCleanHeaders(headers: Headers) { | |
const newHeaders = new Headers(headers); | |
for (const key of headers.keys()) { | |
if (!key.startsWith('x-fastfn')) { | |
newHeaders.delete(key); | |
} | |
} | |
return newHeaders; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment