UNPKG

gqty

Version:

The No-GraphQL Client for TypeScript

108 lines (105 loc) 3.25 kB
import { GQtyError } from '../Error/index.mjs'; import { Selection } from '../Selection.mjs'; import { $meta } from './meta.mjs'; export { $meta } from './meta.mjs'; import { createObjectAccessor } from './resolve.mjs'; 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.createRoot(key, { aliasLength: context.aliasLength }); selectionCache.set(key, selection); return createObjectAccessor({ context, cache: { data: target[key], expiresAt: Infinity }, selection, type: { __type: key } }); } } ), clearCache: () => { selectionCache.clear(); } }; } const setCache = (accessor, data) => { var _a, _b; const meta = $meta(accessor); if (!meta) { throw new GQtyError(`Subject must be an accessor.`); } data = (_b = (_a = $meta(data)) == null ? void 0 : _a.cache.data) != null ? _b : data; if (!data || typeof data !== "object") { throw new GQtyError( `Data must be a subset of the schema object, got type: ${typeof data}.` ); } meta.cache.data = data; Object.assign(accessor, data); }; const assignSelections = (source, target) => { var _a; if (source === null || target === null) return; if ($meta(source) === void 0) { throw new GQtyError(`Invalid source proxy`); } if ($meta(target) === void 0) { throw new GQtyError(`Invalid target proxy`); } const sourceSelection = (_a = $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 GQtyError( `Unexpected inputs for selection: ${selection}` ); } currentNode = node(selection.input); } else { currentNode = node; } } } } else { for (const [, child] of it.children) { stack.add(child); } } } }; export { assignSelections, createSchemaAccessor, setCache };