1 | import { valueFromAST, isNonNullType, Kind, print, } from 'graphql';
|
2 | import { createGraphQLError } from './errors.js';
|
3 | import { inspect } from './inspect.js';
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | export function getArgumentValues(def, node, variableValues = {}) {
|
13 | var _a;
|
14 | const variableMap = Object.entries(variableValues).reduce((prev, [key, value]) => ({
|
15 | ...prev,
|
16 | [key]: value,
|
17 | }), {});
|
18 | const coercedValues = {};
|
19 | const argumentNodes = (_a = node.arguments) !== null && _a !== void 0 ? _a : [];
|
20 | const argNodeMap = argumentNodes.reduce((prev, arg) => ({
|
21 | ...prev,
|
22 | [arg.name.value]: arg,
|
23 | }), {});
|
24 | for (const { name, type: argType, defaultValue } of def.args) {
|
25 | const argumentNode = argNodeMap[name];
|
26 | if (!argumentNode) {
|
27 | if (defaultValue !== undefined) {
|
28 | coercedValues[name] = defaultValue;
|
29 | }
|
30 | else if (isNonNullType(argType)) {
|
31 | throw createGraphQLError(`Argument "${name}" of required type "${inspect(argType)}" ` + 'was not provided.', {
|
32 | nodes: [node],
|
33 | });
|
34 | }
|
35 | continue;
|
36 | }
|
37 | const valueNode = argumentNode.value;
|
38 | let isNull = valueNode.kind === Kind.NULL;
|
39 | if (valueNode.kind === Kind.VARIABLE) {
|
40 | const variableName = valueNode.name.value;
|
41 | if (variableValues == null || variableMap[variableName] == null) {
|
42 | if (defaultValue !== undefined) {
|
43 | coercedValues[name] = defaultValue;
|
44 | }
|
45 | else if (isNonNullType(argType)) {
|
46 | throw createGraphQLError(`Argument "${name}" of required type "${inspect(argType)}" ` +
|
47 | `was provided the variable "$${variableName}" which was not provided a runtime value.`, {
|
48 | nodes: [valueNode],
|
49 | });
|
50 | }
|
51 | continue;
|
52 | }
|
53 | isNull = variableValues[variableName] == null;
|
54 | }
|
55 | if (isNull && isNonNullType(argType)) {
|
56 | throw createGraphQLError(`Argument "${name}" of non-null type "${inspect(argType)}" ` + 'must not be null.', {
|
57 | nodes: [valueNode],
|
58 | });
|
59 | }
|
60 | const coercedValue = valueFromAST(valueNode, argType, variableValues);
|
61 | if (coercedValue === undefined) {
|
62 |
|
63 |
|
64 |
|
65 | throw createGraphQLError(`Argument "${name}" has invalid value ${print(valueNode)}.`, {
|
66 | nodes: [valueNode],
|
67 | });
|
68 | }
|
69 | coercedValues[name] = coercedValue;
|
70 | }
|
71 | return coercedValues;
|
72 | }
|