gqty
Version:
The No-GraphQL Client for TypeScript
55 lines (52 loc) • 1.57 kB
JavaScript
import { fromJSON } from 'flatted';
import { GQtyError } from '../../Error/index.mjs';
import '../../Utils/hash.mjs';
import { $meta } from '../../Accessor/meta.mjs';
import '../../Accessor/resolve.mjs';
import { fetchSelections } from '../resolveSelections.mjs';
import { updateCaches } from '../updateCaches.mjs';
import { isLegacyCacheSnapshot } from './prepareRender.mjs';
const createLegacyHydrateCache = ({
accessor,
cache,
fetchOptions
}) => ({ cacheSnapshot, shouldRefetch = false }) => {
const { cache: snapshot, selections: selectionSnapshots } = parseSnapshot(cacheSnapshot);
if (snapshot) {
cache.restore(snapshot);
}
if (selectionSnapshots && shouldRefetch) {
const selections = /* @__PURE__ */ new Set();
for (const [[root], ...snapshot2] of selectionSnapshots) {
const { selection } = $meta(
accessor[root]
);
selections.add(selection.fromJSON(snapshot2));
}
setTimeout(
() => {
fetchSelections(selections, {
cache,
fetchOptions: {
...fetchOptions,
cachePolicy: "no-cache"
// refetch
}
}).then((results) => updateCaches(results, [cache]));
},
shouldRefetch === true ? 0 : shouldRefetch
);
}
};
const parseSnapshot = (snapshot) => {
try {
const data = fromJSON(snapshot);
if (!isLegacyCacheSnapshot(data)) {
throw 1;
}
return data;
} catch {
throw new GQtyError(`Unrecognized snapshot format.`);
}
};
export { createLegacyHydrateCache, parseSnapshot };