SingleFieldSubscriptionsRule.js.flow 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. // @flow strict
  2. import { GraphQLError } from '../../error/GraphQLError';
  3. import type { ASTVisitor } from '../../language/visitor';
  4. import type { OperationDefinitionNode } from '../../language/ast';
  5. import type { ASTValidationContext } from '../ValidationContext';
  6. /**
  7. * Subscriptions must only include one field.
  8. *
  9. * A GraphQL subscription is valid only if it contains a single root field.
  10. */
  11. export function SingleFieldSubscriptionsRule(
  12. context: ASTValidationContext,
  13. ): ASTVisitor {
  14. return {
  15. OperationDefinition(node: OperationDefinitionNode) {
  16. if (node.operation === 'subscription') {
  17. if (node.selectionSet.selections.length !== 1) {
  18. context.reportError(
  19. new GraphQLError(
  20. node.name
  21. ? `Subscription "${node.name.value}" must select only one top level field.`
  22. : 'Anonymous Subscription must select only one top level field.',
  23. node.selectionSet.selections.slice(1),
  24. ),
  25. );
  26. }
  27. }
  28. },
  29. };
  30. }