@apollo/client
Version:
A fully-featured caching GraphQL client.
67 lines (66 loc) • 3.01 kB
JavaScript
import { invariant } from "@apollo/client/utilities/invariant";
import { createFragmentMap } from "./createFragmentMap.js";
import { getFragmentDefinitions } from "./getFragmentDefinitions.js";
import { getFragmentFromSelection } from "./getFragmentFromSelection.js";
import { getMainDefinition } from "./getMainDefinition.js";
import { getOperationDefinition } from "./getOperationDefinition.js";
import { isField } from "./isField.js";
import { resultKeyNameFromField } from "./resultKeyNameFromField.js";
/**
* @internal
*
* @deprecated This is an internal API and should not be used directly. This can be removed or changed at any time.
*/
export function coerceScalarFieldsToParsed(result, query, cache) {
const operationType = getOperationDefinition(query)?.operation;
const fragmentMap = createFragmentMap(getFragmentDefinitions(query));
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 (isField(selection)) {
const resultName = 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 = getFragmentFromSelection(selection, fragmentMap);
if (fragment && typename && cache.fragmentMatches(fragment, typename)) {
fragment.selectionSet.selections.forEach((s) => workSet.add(s));
}
}
});
return changed ? result : data;
}
return coerceSelectionSet(getMainDefinition(query).selectionSet, result, cache.getRootTypename(operationType));
}
//# sourceMappingURL=coerceScalarFieldsToParsed.js.map