UNPKG

gqty

Version:

The No-GraphQL Client for TypeScript

114 lines (109 loc) 3.45 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const index = require('../Error/index.js'); const Selection = require('../Selection.js'); const meta = require('./meta.js'); const resolve = require('./resolve.js'); function createSchemaAccessor(context) { const selectionCache = /* @__PURE__ */ new Map(); return { accessor: new Proxy( { query: { __typename: "Query" }, mutation: { __typename: "Mutation" }, subscription: { __typename: "Subscription" } }, { get(target, key) { var _a; if (key === "toJSON") { return () => context.cache.toJSON(); } if (!Reflect.has(target, key) || !Reflect.get( target[key], "__typename" ) || !context.schema[key]) return; const selection = (_a = selectionCache.get(key)) != null ? _a : Selection.Selection.createRoot(key, { aliasLength: context.aliasLength }); selectionCache.set(key, selection); return resolve.createObjectAccessor({ context, cache: { data: target[key], expiresAt: Infinity }, selection, type: { __type: key } }); } } ), clearCache: () => { selectionCache.clear(); } }; } const setCache = (accessor, data) => { var _a, _b; const meta$1 = meta.$meta(accessor); if (!meta$1) { throw new index.GQtyError(`Subject must be an accessor.`); } data = (_b = (_a = meta.$meta(data)) == null ? void 0 : _a.cache.data) != null ? _b : data; if (!data || typeof data !== "object") { throw new index.GQtyError( `Data must be a subset of the schema object, got type: ${typeof data}.` ); } meta$1.cache.data = data; Object.assign(accessor, data); }; const assignSelections = (source, target) => { var _a; if (source === null || target === null) return; if (meta.$meta(source) === void 0) { throw new index.GQtyError(`Invalid source proxy`); } if (meta.$meta(target) === void 0) { throw new index.GQtyError(`Invalid target proxy`); } const sourceSelection = (_a = meta.$meta(source)) == null ? void 0 : _a.selection; if (!sourceSelection) return; if (sourceSelection.children.size === 0) { if (process.env.NODE_ENV !== "production") { console.warn("Source proxy doesn't have any selections made"); } } const stack = new Set(sourceSelection.children.values()); for (const it of stack) { if (it.children.size === 0) { let currentNode; for (const selection of it.ancestry) { if (currentNode === void 0) { if (selection !== sourceSelection) continue; currentNode = target; } else { const node = currentNode[selection.key]; if (selection.input) { if (typeof node !== "function") { throw new index.GQtyError( `Unexpected inputs for selection: ${selection}` ); } currentNode = node(selection.input); } else { currentNode = node; } } } } else { for (const [, child] of it.children) { stack.add(child); } } } }; exports.$meta = meta.$meta; exports.assignSelections = assignSelections; exports.createSchemaAccessor = createSchemaAccessor; exports.setCache = setCache;