import { serverCache } from 'rntwsc/cache' import type { UseFetch } from 'rntwsc/fetch/config' import { hk, sck } from 'rntwsc/fetch/config' import type { HydrationData, UseHydrationData } from 'rntwsc/hydration/config' import { dehydrate } from 'rntwsc/hydration/dehydrate' const getCache = () => serverCache(sck.fetch, () => new Map>>()) export const useFetch = async ({ url, headers, }: UseFetch): Promise> => { const k = hk.key({ url, headers, }) const m = getCache() let p = m.get(k) if (!p) { p = fetchWithoutCache({ url, headers, }) m.set(k, p) } const v = await p return dehydrate(k, v) } const fetchWithoutCache = async ({ url, headers, }: UseFetch): Promise> => { try { const r = await fetch(url, { headers, }) if (!r.ok) { throw new Error(`${r.status} ${r.statusText}`) } return { data: await r.json(), } } catch (err) { return { error: String(err), } } }