PossibleFragmentSpreadsRule.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true,
  4. });
  5. exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule;
  6. var _inspect = require('../../jsutils/inspect.js');
  7. var _GraphQLError = require('../../error/GraphQLError.js');
  8. var _definition = require('../../type/definition.js');
  9. var _typeComparators = require('../../utilities/typeComparators.js');
  10. var _typeFromAST = require('../../utilities/typeFromAST.js');
  11. /**
  12. * Possible fragment spread
  13. *
  14. * A fragment spread is only valid if the type condition could ever possibly
  15. * be true: if there is a non-empty intersection of the possible parent types,
  16. * and possible types which pass the type condition.
  17. */
  18. function PossibleFragmentSpreadsRule(context) {
  19. return {
  20. InlineFragment(node) {
  21. const fragType = context.getType();
  22. const parentType = context.getParentType();
  23. if (
  24. (0, _definition.isCompositeType)(fragType) &&
  25. (0, _definition.isCompositeType)(parentType) &&
  26. !(0, _typeComparators.doTypesOverlap)(
  27. context.getSchema(),
  28. fragType,
  29. parentType,
  30. )
  31. ) {
  32. const parentTypeStr = (0, _inspect.inspect)(parentType);
  33. const fragTypeStr = (0, _inspect.inspect)(fragType);
  34. context.reportError(
  35. new _GraphQLError.GraphQLError(
  36. `Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`,
  37. {
  38. nodes: node,
  39. },
  40. ),
  41. );
  42. }
  43. },
  44. FragmentSpread(node) {
  45. const fragName = node.name.value;
  46. const fragType = getFragmentType(context, fragName);
  47. const parentType = context.getParentType();
  48. if (
  49. fragType &&
  50. parentType &&
  51. !(0, _typeComparators.doTypesOverlap)(
  52. context.getSchema(),
  53. fragType,
  54. parentType,
  55. )
  56. ) {
  57. const parentTypeStr = (0, _inspect.inspect)(parentType);
  58. const fragTypeStr = (0, _inspect.inspect)(fragType);
  59. context.reportError(
  60. new _GraphQLError.GraphQLError(
  61. `Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`,
  62. {
  63. nodes: node,
  64. },
  65. ),
  66. );
  67. }
  68. },
  69. };
  70. }
  71. function getFragmentType(context, name) {
  72. const frag = context.getFragment(name);
  73. if (frag) {
  74. const type = (0, _typeFromAST.typeFromAST)(
  75. context.getSchema(),
  76. frag.typeCondition,
  77. );
  78. if ((0, _definition.isCompositeType)(type)) {
  79. return type;
  80. }
  81. }
  82. }