UNPKG

@graphql-mesh/utils

Version:
73 lines (72 loc) 3.07 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getRootFieldsWithArgs = void 0; const graphql_1 = require("graphql"); const utils_1 = require("@graphql-tools/utils"); const getOperationsAndFragments_js_1 = require("./getOperationsAndFragments.js"); function getRootFieldsWithArgs(schema, executionRequest) { const rootTypeMap = (0, utils_1.getRootTypeMap)(schema); const { document, variables, operationName } = executionRequest; const { operations, fragments } = (0, getOperationsAndFragments_js_1.getOperationsAndFragments)(document); const actualOperationName = operationName || Object.keys(operations)[0]; const operation = operations[actualOperationName]; if (!operation) { throw new graphql_1.GraphQLError(`No operation found with name ${actualOperationName}`); } const operationType = operation.operation; const rootType = rootTypeMap.get(operationType); if (!rootType) { throw new graphql_1.GraphQLError(`No root type found for operation type ${operationType}`); } const rootFieldMap = rootType.getFields(); const rootFieldsWithArgs = new Map(); const coercedVariables = (0, graphql_1.getVariableValues)(schema, operation.variableDefinitions || [], variables || {}); if (coercedVariables.errors) { throw new AggregateError(coercedVariables.errors); } const selectionHandlerCtx = { rootFieldMap, rootFieldsWithArgs, fragments, variables: coercedVariables.coerced, }; for (const selection of operation.selectionSet.selections) { handleSelection(selection, selectionHandlerCtx); } return rootFieldsWithArgs; } exports.getRootFieldsWithArgs = getRootFieldsWithArgs; function handleFieldNode(fieldNode, ctx) { const originalFieldName = fieldNode.name.value; const rootField = ctx.rootFieldMap[originalFieldName]; if (!rootField) { throw new graphql_1.GraphQLError(`No root field found for field ${originalFieldName}`); } const args = (0, graphql_1.getArgumentValues)(rootField, fieldNode, ctx.variables); ctx.rootFieldsWithArgs.set(originalFieldName, args); } function handleSelection(selection, ctx) { switch (selection.kind) { case graphql_1.Kind.FIELD: { handleFieldNode(selection, ctx); break; } case graphql_1.Kind.FRAGMENT_SPREAD: { const fragmentName = selection.name.value; const fragment = ctx.fragments[fragmentName]; if (!fragment) { throw new graphql_1.GraphQLError(`Fragment ${fragmentName} not found`); } for (const fragmentSelection of fragment.selectionSet.selections) { handleSelection(fragmentSelection, ctx); } break; } case graphql_1.Kind.INLINE_FRAGMENT: { for (const inlineSelection of selection.selectionSet.selections) { handleSelection(inlineSelection, ctx); } break; } } }