LoneAnonymousOperationRule.mjs 947 B

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