UNPKG

gqty

Version:

The No-GraphQL Client for TypeScript

106 lines (101 loc) 3.17 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const flatted = require('flatted'); const frailMap = require('frail-map'); const deepCopy = require('../Helpers/deepCopy.js'); require('../Utils/hash.js'); const object = require('../Utils/object.js'); const crawl = require('./crawl.js'); const normalization = require('./normalization.js'); const isCacheSnapshotObject = (value) => object.isPlainObject(value) && typeof value.__typename === "string"; const isCacheReference = (value) => object.isPlainObject(value) && typeof value.__ref === "string"; const importCacheSnapshot = (snapshot, options) => { const { query, mutation, subscription, normalized = {} } = deepCopy.deepCopy(snapshot); const seen = /* @__PURE__ */ new Set(); const data = crawl.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 = normalization.normalizeObject(value, { ...options, store }); if (norbject !== void 0) { store.set(key, norbject); } return store; }, new frailMap.FrailMap() ); } return data; }; const exportCacheSnapshot = ({ query, mutation, subscription }, options) => { const snapshot = flatted.fromJSON( flatted.toJSON({ query, mutation, subscription }) ); if (options) { const normalized = {}; crawl.crawl(snapshot, (it, key, parent) => { const id = options == null ? void 0 : options.identity(it); if (!id) return; if (!normalized[id]) { normalized[id] = normalization.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; } } }); exports.createPersistors = createPersistors; exports.exportCacheSnapshot = exportCacheSnapshot; exports.importCacheSnapshot = importCacheSnapshot; exports.isCacheReference = isCacheReference; exports.isCacheSnapshotObject = isCacheSnapshotObject;