UNPKG

@apollo/client

Version:

A fully-featured caching GraphQL client.

70 lines (69 loc) 3.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.coerceScalarFieldsToParsed = coerceScalarFieldsToParsed; const invariant_1 = require("@apollo/client/utilities/invariant"); const createFragmentMap_js_1 = require("./createFragmentMap.cjs"); const getFragmentDefinitions_js_1 = require("./getFragmentDefinitions.cjs"); const getFragmentFromSelection_js_1 = require("./getFragmentFromSelection.cjs"); const getMainDefinition_js_1 = require("./getMainDefinition.cjs"); const getOperationDefinition_js_1 = require("./getOperationDefinition.cjs"); const isField_js_1 = require("./isField.cjs"); const resultKeyNameFromField_js_1 = require("./resultKeyNameFromField.cjs"); /** * @internal * * @deprecated This is an internal API and should not be used directly. This can be removed or changed at any time. */ function coerceScalarFieldsToParsed(result, query, cache) { const operationType = (0, getOperationDefinition_js_1.getOperationDefinition)(query)?.operation; const fragmentMap = (0, createFragmentMap_js_1.createFragmentMap)((0, getFragmentDefinitions_js_1.getFragmentDefinitions)(query)); (0, invariant_1.invariant)(operationType, 6); function coerceField(field, fieldValue, typename) { let changed = false; if (Array.isArray(fieldValue)) { const items = fieldValue.map((item) => { const coerced = coerceField(field, item, typename); changed ||= coerced !== item; return coerced; }); return changed ? items : fieldValue; } if (field.selectionSet) { return coerceSelectionSet(field.selectionSet, fieldValue); } if (fieldValue === null || !typename) return fieldValue; const scalar = cache.getScalarForField(typename, field.name.value); return scalar ? scalar.coerceToParsed(fieldValue) : fieldValue; } function coerceSelectionSet(selectionSet, data, typename) { if (data === null || typeof data !== "object") return data; const result = { ...data }; let changed = false; if (Object.hasOwn(data, "__typename")) { typename = data.__typename; } const workSet = new Set(selectionSet.selections); workSet.forEach((selection) => { if ((0, isField_js_1.isField)(selection)) { const resultName = (0, resultKeyNameFromField_js_1.resultKeyNameFromField)(selection); if (!Object.hasOwn(data, resultName)) return; const fieldValue = data[resultName]; const coerced = coerceField(selection, fieldValue, typename); changed ||= coerced !== fieldValue; result[resultName] = coerced; } else { const fragment = (0, getFragmentFromSelection_js_1.getFragmentFromSelection)(selection, fragmentMap); if (fragment && typename && cache.fragmentMatches(fragment, typename)) { fragment.selectionSet.selections.forEach((s) => workSet.add(s)); } } }); return changed ? result : data; } return coerceSelectionSet((0, getMainDefinition_js_1.getMainDefinition)(query).selectionSet, result, cache.getRootTypename(operationType)); } //# sourceMappingURL=coerceScalarFieldsToParsed.cjs.map