1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import inspect from '../../jsutils/inspect';
- import { GraphQLError } from '../../error/GraphQLError';
- import { Kind } from '../../language/kinds';
- import type { ValueNode } from '../../language/ast';
- import type { ASTVisitor } from '../../language/visitor';
- import type { GraphQLSchema } from '../../type/schema';
- import type { GraphQLType } from '../../type/definition';
- import { isNonNullType } from '../../type/definition';
- import { typeFromAST } from '../../utilities/typeFromAST';
- import { isTypeSubTypeOf } from '../../utilities/typeComparators';
- import type { ValidationContext } from '../ValidationContext';
- export function VariablesInAllowedPositionRule(
- context: ValidationContext,
- ): ASTVisitor {
- let varDefMap = Object.create(null);
- return {
- OperationDefinition: {
- enter() {
- varDefMap = Object.create(null);
- },
- leave(operation) {
- const usages = context.getRecursiveVariableUsages(operation);
- for (const { node, type, defaultValue } of usages) {
- const varName = node.name.value;
- const varDef = varDefMap[varName];
- if (varDef && type) {
-
-
-
-
-
- const schema = context.getSchema();
- const varType = typeFromAST(schema, varDef.type);
- if (
- varType &&
- !allowedVariableUsage(
- schema,
- varType,
- varDef.defaultValue,
- type,
- defaultValue,
- )
- ) {
- const varTypeStr = inspect(varType);
- const typeStr = inspect(type);
- context.reportError(
- new GraphQLError(
- `Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`,
- [varDef, node],
- ),
- );
- }
- }
- }
- },
- },
- VariableDefinition(node) {
- varDefMap[node.variable.name.value] = node;
- },
- };
- }
- function allowedVariableUsage(
- schema: GraphQLSchema,
- varType: GraphQLType,
- varDefaultValue: ?ValueNode,
- locationType: GraphQLType,
- locationDefaultValue: ?mixed,
- ): boolean {
- if (isNonNullType(locationType) && !isNonNullType(varType)) {
- const hasNonNullVariableDefaultValue =
- varDefaultValue != null && varDefaultValue.kind !== Kind.NULL;
- const hasLocationDefaultValue = locationDefaultValue !== undefined;
- if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) {
- return false;
- }
- const nullableLocationType = locationType.ofType;
- return isTypeSubTypeOf(schema, varType, nullableLocationType);
- }
- return isTypeSubTypeOf(schema, varType, locationType);
- }
|