Skip to content

Instantly share code, notes, and snippets.

@unnoq
Last active June 15, 2024 07:50
Show Gist options
  • Save unnoq/3c1448d39f4c03d93e935f02efec8be4 to your computer and use it in GitHub Desktop.
Save unnoq/3c1448d39f4c03d93e935f02efec8be4 to your computer and use it in GitHub Desktop.
better-fetch
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