SingleFieldSubscriptions.js.flow 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. export function singleFieldOnlyMessage(name: ?string): string {
  7. return name
  8. ? `Subscription "${name}" must select only one top level field.`
  9. : 'Anonymous Subscription must select only one top level field.';
  10. }
  11. /**
  12. * Subscriptions must only include one field.
  13. *
  14. * A GraphQL subscription is valid only if it contains a single root field.
  15. */
  16. export function SingleFieldSubscriptions(
  17. context: ASTValidationContext,
  18. ): ASTVisitor {
  19. return {
  20. OperationDefinition(node: OperationDefinitionNode) {
  21. if (node.operation === 'subscription') {
  22. if (node.selectionSet.selections.length !== 1) {
  23. context.reportError(
  24. new GraphQLError(
  25. singleFieldOnlyMessage(node.name && node.name.value),
  26. node.selectionSet.selections.slice(1),
  27. ),
  28. );
  29. }
  30. }
  31. },
  32. };
  33. }