PossibleFragmentSpreadsRule.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import inspect from "../../jsutils/inspect.mjs";
  2. import { GraphQLError } from "../../error/GraphQLError.mjs";
  3. import { isCompositeType } from "../../type/definition.mjs";
  4. import { typeFromAST } from "../../utilities/typeFromAST.mjs";
  5. import { doTypesOverlap } from "../../utilities/typeComparators.mjs";
  6. /**
  7. * Possible fragment spread
  8. *
  9. * A fragment spread is only valid if the type condition could ever possibly
  10. * be true: if there is a non-empty intersection of the possible parent types,
  11. * and possible types which pass the type condition.
  12. */
  13. export function PossibleFragmentSpreadsRule(context) {
  14. return {
  15. InlineFragment: function InlineFragment(node) {
  16. var fragType = context.getType();
  17. var parentType = context.getParentType();
  18. if (isCompositeType(fragType) && isCompositeType(parentType) && !doTypesOverlap(context.getSchema(), fragType, parentType)) {
  19. var parentTypeStr = inspect(parentType);
  20. var fragTypeStr = inspect(fragType);
  21. context.reportError(new GraphQLError("Fragment cannot be spread here as objects of type \"".concat(parentTypeStr, "\" can never be of type \"").concat(fragTypeStr, "\"."), node));
  22. }
  23. },
  24. FragmentSpread: function FragmentSpread(node) {
  25. var fragName = node.name.value;
  26. var fragType = getFragmentType(context, fragName);
  27. var parentType = context.getParentType();
  28. if (fragType && parentType && !doTypesOverlap(context.getSchema(), fragType, parentType)) {
  29. var parentTypeStr = inspect(parentType);
  30. var fragTypeStr = inspect(fragType);
  31. context.reportError(new GraphQLError("Fragment \"".concat(fragName, "\" cannot be spread here as objects of type \"").concat(parentTypeStr, "\" can never be of type \"").concat(fragTypeStr, "\"."), node));
  32. }
  33. }
  34. };
  35. }
  36. function getFragmentType(context, name) {
  37. var frag = context.getFragment(name);
  38. if (frag) {
  39. var type = typeFromAST(context.getSchema(), frag.typeCondition);
  40. if (isCompositeType(type)) {
  41. return type;
  42. }
  43. }
  44. }