LoneAnonymousOperationRule.js.flow 1010 B

123456789101112131415161718192021222324252627282930313233343536
  1. // @flow strict
  2. import { GraphQLError } from '../../error/GraphQLError';
  3. import type { ASTVisitor } from '../../language/visitor';
  4. import { Kind } from '../../language/kinds';
  5. import type { ASTValidationContext } from '../ValidationContext';
  6. /**
  7. * Lone anonymous operation
  8. *
  9. * A GraphQL document is only valid if when it contains an anonymous operation
  10. * (the query short-hand) that it contains only that one operation definition.
  11. */
  12. export function LoneAnonymousOperationRule(
  13. context: ASTValidationContext,
  14. ): ASTVisitor {
  15. let operationCount = 0;
  16. return {
  17. Document(node) {
  18. operationCount = node.definitions.filter(
  19. (definition) => definition.kind === Kind.OPERATION_DEFINITION,
  20. ).length;
  21. },
  22. OperationDefinition(node) {
  23. if (!node.name && operationCount > 1) {
  24. context.reportError(
  25. new GraphQLError(
  26. 'This anonymous operation must be the only defined operation.',
  27. node,
  28. ),
  29. );
  30. }
  31. },
  32. };
  33. }