gqty
Version:
The No-GraphQL Client for TypeScript
98 lines (95 loc) • 2.9 kB
JavaScript
import { fromJSON, toJSON } from 'flatted';
import { FrailMap } from 'frail-map';
import { deepCopy } from '../Helpers/deepCopy.mjs';
import '../Utils/hash.mjs';
import { isPlainObject } from '../Utils/object.mjs';
import { crawl } from './crawl.mjs';
import { normalizeObject, isNormalizedObjectShell } from './normalization.mjs';
const isCacheSnapshotObject = (value) => isPlainObject(value) && typeof value.__typename === "string";
const isCacheReference = (value) => isPlainObject(value) && typeof value.__ref === "string";
const importCacheSnapshot = (snapshot, options) => {
const { query, mutation, subscription, normalized = {} } = deepCopy(snapshot);
const seen = /* @__PURE__ */ new Set();
const data = crawl(
{ query, mutation, subscription },
(it, key, parent) => {
if (isCacheReference(it)) {
const norbj = normalized[it.__ref];
Reflect.set(parent, key, norbj);
if (!seen.has(norbj)) {
seen.add(norbj);
return [norbj, 0, []];
}
}
return;
}
);
if (options) {
data.normalizedObjects = Object.entries(normalized).reduce(
(store, [key, value]) => {
const norbject = normalizeObject(value, {
...options,
store
});
if (norbject !== void 0) {
store.set(key, norbject);
}
return store;
},
new FrailMap()
);
}
return data;
};
const exportCacheSnapshot = ({ query, mutation, subscription }, options) => {
const snapshot = fromJSON(
toJSON({ query, mutation, subscription })
);
if (options) {
const normalized = {};
crawl(snapshot, (it, key, parent) => {
const id = options == null ? void 0 : options.identity(it);
if (!id) return;
if (!normalized[id]) {
normalized[id] = isNormalizedObjectShell(it) ? it.toJSON() : it;
}
Reflect.set(parent, key, { __ref: id });
});
if (Object.keys(normalized).length > 0) {
snapshot.normalized = normalized;
}
}
return snapshot;
};
const createPersistors = (cache) => ({
persist(version) {
const snapshot = cache.toJSON();
if (version !== void 0) {
snapshot.version = version;
}
return snapshot;
},
restore(data, version) {
if (data.version !== version || version !== void 0 && typeof version !== "string") {
console.warn(`[GQty] Cache version mismatch, ignored.`);
return false;
}
if (data == null || typeof data !== "object" || Array.isArray(data)) {
return false;
}
try {
cache.restore(data);
} catch (e) {
console.warn(e);
}
return true;
},
async restoreAsync(data, version) {
try {
return this.restore(await data(), version);
} catch {
return false;
}
}
});
export { createPersistors, exportCacheSnapshot, importCacheSnapshot, isCacheReference, isCacheSnapshotObject };