getOperationAST.js.flow 1.0 KB

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