1 | import { inspect } from 'cross-inspect';
|
2 | import { isNonNullType, Kind, print, valueFromAST, } from 'graphql';
|
3 | import { createGraphQLError } from './errors.js';
|
4 | import { hasOwnProperty } from './jsutils.js';
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | export 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 |
|
59 |
|
60 |
|
61 | throw createGraphQLError(`Argument "${name}" has invalid value ${print(valueNode)}.`, {
|
62 | nodes: [valueNode],
|
63 | });
|
64 | }
|
65 | coercedValues[name] = coercedValue;
|
66 | }
|
67 | return coercedValues;
|
68 | }
|