UNPKG

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