UNPKG

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