LoneAnonymousOperation.js.flow 1.0 KB

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