UNPKG

2.95 kBJavaScriptView Raw
1import inspect from "../../jsutils/inspect.mjs";
2import { GraphQLError } from "../../error/GraphQLError.mjs";
3import { Kind } from "../../language/kinds.mjs";
4import { isNonNullType } from "../../type/definition.mjs";
5import { typeFromAST } from "../../utilities/typeFromAST.mjs";
6import { isTypeSubTypeOf } from "../../utilities/typeComparators.mjs";
7
8/**
9 * Variables passed to field arguments conform to type
10 */
11export 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 // A var type is allowed if it is the same or more strict (e.g. is
31 // a subtype of) than the expected type. It can be more strict if
32 // the variable type is non-null when the expected type is nullable.
33 // If both are list types, the variable item type can be more strict
34 // than the expected item type (contravariant).
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 * Returns true if the variable is allowed in the location it was found,
54 * which includes considering if default values exist for either the variable
55 * or the location at which it is located.
56 */
57
58function 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}