PossibleFragmentSpreads.mjs 2.1 KB

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