UNPKG

3.37 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.getArgumentValues = void 0;
4const cross_inspect_1 = require("cross-inspect");
5const graphql_1 = require("graphql");
6const errors_js_1 = require("./errors.js");
7const jsutils_js_1 = require("./jsutils.js");
8/**
9 * Prepares an object map of argument values given a list of argument
10 * definitions and list of argument AST nodes.
11 *
12 * Note: The returned value is a plain Object with a prototype, since it is
13 * exposed to user code. Care should be taken to not pull values from the
14 * Object prototype.
15 */
16function getArgumentValues(def, node, variableValues = {}) {
17 const coercedValues = {};
18 const argumentNodes = node.arguments ?? [];
19 const argNodeMap = argumentNodes.reduce((prev, arg) => ({
20 ...prev,
21 [arg.name.value]: arg,
22 }), {});
23 for (const { name, type: argType, defaultValue } of def.args) {
24 const argumentNode = argNodeMap[name];
25 if (!argumentNode) {
26 if (defaultValue !== undefined) {
27 coercedValues[name] = defaultValue;
28 }
29 else if ((0, graphql_1.isNonNullType)(argType)) {
30 throw (0, errors_js_1.createGraphQLError)(`Argument "${name}" of required type "${(0, cross_inspect_1.inspect)(argType)}" ` + 'was not provided.', {
31 nodes: [node],
32 });
33 }
34 continue;
35 }
36 const valueNode = argumentNode.value;
37 let isNull = valueNode.kind === graphql_1.Kind.NULL;
38 if (valueNode.kind === graphql_1.Kind.VARIABLE) {
39 const variableName = valueNode.name.value;
40 if (variableValues == null || !(0, jsutils_js_1.hasOwnProperty)(variableValues, variableName)) {
41 if (defaultValue !== undefined) {
42 coercedValues[name] = defaultValue;
43 }
44 else if ((0, graphql_1.isNonNullType)(argType)) {
45 throw (0, errors_js_1.createGraphQLError)(`Argument "${name}" of required type "${(0, cross_inspect_1.inspect)(argType)}" ` +
46 `was provided the variable "$${variableName}" which was not provided a runtime value.`, {
47 nodes: [valueNode],
48 });
49 }
50 continue;
51 }
52 isNull = variableValues[variableName] == null;
53 }
54 if (isNull && (0, graphql_1.isNonNullType)(argType)) {
55 throw (0, errors_js_1.createGraphQLError)(`Argument "${name}" of non-null type "${(0, cross_inspect_1.inspect)(argType)}" ` + 'must not be null.', {
56 nodes: [valueNode],
57 });
58 }
59 const coercedValue = (0, graphql_1.valueFromAST)(valueNode, argType, variableValues);
60 if (coercedValue === undefined) {
61 // Note: ValuesOfCorrectTypeRule validation should catch this before
62 // execution. This is a runtime check to ensure execution does not
63 // continue with an invalid argument value.
64 throw (0, errors_js_1.createGraphQLError)(`Argument "${name}" has invalid value ${(0, graphql_1.print)(valueNode)}.`, {
65 nodes: [valueNode],
66 });
67 }
68 coercedValues[name] = coercedValue;
69 }
70 return coercedValues;
71}
72exports.getArgumentValues = getArgumentValues;