1 | import inspect from "../../jsutils/inspect.mjs";
|
2 | import { GraphQLError } from "../../error/GraphQLError.mjs";
|
3 | import { Kind } from "../../language/kinds.mjs";
|
4 | import { isNonNullType } from "../../type/definition.mjs";
|
5 | import { typeFromAST } from "../../utilities/typeFromAST.mjs";
|
6 | import { isTypeSubTypeOf } from "../../utilities/typeComparators.mjs";
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | export function VariablesInAllowedPositionRule(context) {
|
12 | var varDefMap = Object.create(null);
|
13 | return {
|
14 | OperationDefinition: {
|
15 | enter: function enter() {
|
16 | varDefMap = Object.create(null);
|
17 | },
|
18 | leave: function leave(operation) {
|
19 | var usages = context.getRecursiveVariableUsages(operation);
|
20 |
|
21 | for (var _i2 = 0; _i2 < usages.length; _i2++) {
|
22 | var _ref2 = usages[_i2];
|
23 | var node = _ref2.node;
|
24 | var type = _ref2.type;
|
25 | var defaultValue = _ref2.defaultValue;
|
26 | var varName = node.name.value;
|
27 | var varDef = varDefMap[varName];
|
28 |
|
29 | if (varDef && type) {
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | var schema = context.getSchema();
|
36 | var varType = typeFromAST(schema, varDef.type);
|
37 |
|
38 | if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) {
|
39 | var varTypeStr = inspect(varType);
|
40 | var typeStr = inspect(type);
|
41 | context.reportError(new GraphQLError("Variable \"$".concat(varName, "\" of type \"").concat(varTypeStr, "\" used in position expecting type \"").concat(typeStr, "\"."), [varDef, node]));
|
42 | }
|
43 | }
|
44 | }
|
45 | }
|
46 | },
|
47 | VariableDefinition: function VariableDefinition(node) {
|
48 | varDefMap[node.variable.name.value] = node;
|
49 | }
|
50 | };
|
51 | }
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 | function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) {
|
59 | if (isNonNullType(locationType) && !isNonNullType(varType)) {
|
60 | var hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== Kind.NULL;
|
61 | var hasLocationDefaultValue = locationDefaultValue !== undefined;
|
62 |
|
63 | if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) {
|
64 | return false;
|
65 | }
|
66 |
|
67 | var nullableLocationType = locationType.ofType;
|
68 | return isTypeSubTypeOf(schema, varType, nullableLocationType);
|
69 | }
|
70 |
|
71 | return isTypeSubTypeOf(schema, varType, locationType);
|
72 | }
|