import { print } from 'graphql' import { serverCache } from 'rntwsc/cache' import type { GraphQLResponse, UseApollo } from 'rntwsc/graphql/config' import { hk, normalizeGraphQLResponse, sck } from 'rntwsc/graphql/config' import type { HydrationData, UseHydrationData } from 'rntwsc/hydration/config' import { dehydrate } from 'rntwsc/hydration/dehydrate' import { jsonSafe } from 'rntwsc/libs/json-safe' const getCache = () => serverCache( sck.fetch, () => new Map>>>(), ) export const useFetchGraphQL = async ({ url, query, variables, headers, }: UseApollo): Promise>> => { const k = hk.key({ url, query, variables, headers, }) const m = getCache() let p = m.get(k) if (!p) { p = fetchWithoutCache({ url, query, variables, headers, }) m.set(k, p) } const v = await p v.data = normalizeGraphQLResponse(v.data) return dehydrate(k, v) } const fetchWithoutCache = async ({ url, query, variables, headers, }: UseApollo): Promise>> => { try { const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers, }, body: jsonSafe({ query: print(query), variables, }), }) if (!r.ok) { throw new Error(`${r.status} ${r.statusText}`) } return { data: await r.json(), } } catch (err) { return { error: String(err), } } }