getOperationAST.js.flow 1016 B

12345678910111213141516171819202122232425262728293031
  1. // @flow strict
  2. import type { DocumentNode, OperationDefinitionNode } from '../language/ast';
  3. import { Kind } from '../language/kinds';
  4. /**
  5. * Returns an operation AST given a document AST and optionally an operation
  6. * name. If a name is not provided, an operation is only returned if only one is
  7. * provided in the document.
  8. */
  9. export function getOperationAST(
  10. documentAST: DocumentNode,
  11. operationName?: ?string,
  12. ): ?OperationDefinitionNode {
  13. let operation = null;
  14. for (const definition of documentAST.definitions) {
  15. if (definition.kind === Kind.OPERATION_DEFINITION) {
  16. if (operationName == null) {
  17. // If no operation name was provided, only return an Operation if there
  18. // is one defined in the document. Upon encountering the second, return
  19. // null.
  20. if (operation) {
  21. return null;
  22. }
  23. operation = definition;
  24. } else if (definition.name?.value === operationName) {
  25. return definition;
  26. }
  27. }
  28. }
  29. return operation;
  30. }