1 type Options<T> = {
2 url: string
3 responseTransformer: (response: Response) => Promise<T>
4 fallbackAction: () => Promise<T>
5 /**
6 * When set, replaces the default URL-based check — `false` forces the
7 * fallback even though the URL is an HTTP one.
8 * Pass `!!process.env.CLOUDFLARE_ENV` for routes that always receive
9 * an HTTP URL but should only fetch remotely on Cloudflare.
10 */
11 useRemote?: boolean
12 }
13
14 /**
15 * Cloudflare Workers don't support the Node.js http/https modules. This
16 * utility abstracts fetch vs. filesystem access so the same code works in
17 * both Cloudflare Workers and local development / Vercel.
18 *
19 * Default behaviour: use `fetch()` when `url` starts with http(s), otherwise
20 * call `fallbackAction` (e.g. read from the local filesystem).
21 *
22 * Pass `useRemote` to override the default check — useful when the URL is
23 * always HTTP but remote fetching should only happen on Cloudflare.
24 */
25 export async function workerCompatibleFetch<T>({
26 url,
27 responseTransformer,
28 fallbackAction,
29 useRemote,
30 }: Options<T>): Promise<T> {
31 // `??`, not `||`: every caller passes `useRemote` as a gate meaning "only
32 // fetch remotely when this is true", and their URL is always an HTTP one, so
33 // `||` made passing `false` a no-op and skipped the fallback entirely.
34 const shouldFetch = useRemote ?? /^https?:\/\//.test(url)
35 if (shouldFetch) {
36 const res = await fetch(url)
37 return await responseTransformer(res)
38 }
39
40 return fallbackAction()
41 }