-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathFragmentsOnCompositeTypesRule.ts
53 lines (48 loc) · 1.65 KB
/
FragmentsOnCompositeTypesRule.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { GraphQLError } from '../../error/GraphQLError';
import { print } from '../../language/printer';
import type { ASTVisitor } from '../../language/visitor';
import { isCompositeType } from '../../type/definition';
import { typeFromAST } from '../../utilities/typeFromAST';
import type { ValidationContext } from '../ValidationContext';
/**
* Fragments on composite type
*
* Fragments use a type condition to determine if they apply, since fragments
* can only be spread into a composite type (object, interface, or union), the
* type condition must also be a composite type.
*
* See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types
*/
export function FragmentsOnCompositeTypesRule(
context: ValidationContext,
): ASTVisitor {
return {
InlineFragment(node) {
const typeCondition = node.typeCondition;
if (typeCondition) {
const type = typeFromAST(context.getSchema(), typeCondition);
if (type && !isCompositeType(type)) {
const typeStr = print(typeCondition);
context.reportError(
new GraphQLError(
`Fragment cannot condition on non composite type "${typeStr}".`,
typeCondition,
),
);
}
}
},
FragmentDefinition(node) {
const type = typeFromAST(context.getSchema(), node.typeCondition);
if (type && !isCompositeType(type)) {
const typeStr = print(node.typeCondition);
context.reportError(
new GraphQLError(
`Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`,
node.typeCondition,
),
);
}
},
};
}