/
SingleFieldSubscriptionsRule.ts
81 lines (77 loc) · 2.91 KB
/
SingleFieldSubscriptionsRule.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import type { ObjMap } from '../../jsutils/ObjMap';
import { GraphQLError } from '../../error/GraphQLError';
import type { ASTVisitor } from '../../language/visitor';
import type {
OperationDefinitionNode,
FragmentDefinitionNode,
} from '../../language/ast';
import { Kind } from '../../language/kinds';
import { collectFields } from '../../execution/collectFields';
import type { ValidationContext } from '../ValidationContext';
/**
* Subscriptions must only include a non-introspection field.
*
* A GraphQL subscription is valid only if it contains a single root field and
* that root field is not an introspection field.
*
* See https://spec.graphql.org/draft/#sec-Single-root-field
*/
export function SingleFieldSubscriptionsRule(
context: ValidationContext,
): ASTVisitor {
return {
OperationDefinition(node: OperationDefinitionNode) {
if (node.operation === 'subscription') {
const schema = context.getSchema();
const subscriptionType = schema.getSubscriptionType();
if (subscriptionType) {
const operationName = node.name ? node.name.value : null;
const variableValues: {
[variable: string]: any;
} = Object.create(null);
const document = context.getDocument();
const fragments: ObjMap<FragmentDefinitionNode> = Object.create(null);
for (const definition of document.definitions) {
if (definition.kind === Kind.FRAGMENT_DEFINITION) {
fragments[definition.name.value] = definition;
}
}
const fields = collectFields(
schema,
fragments,
variableValues,
subscriptionType,
node.selectionSet,
);
if (fields.size > 1) {
const fieldSelectionLists = [...fields.values()];
const extraFieldSelectionLists = fieldSelectionLists.slice(1);
const extraFieldSelections = extraFieldSelectionLists.flat();
context.reportError(
new GraphQLError(
operationName != null
? `Subscription "${operationName}" must select only one top level field.`
: 'Anonymous Subscription must select only one top level field.',
extraFieldSelections,
),
);
}
for (const fieldNodes of fields.values()) {
const field = fieldNodes[0];
const fieldName = field.name.value;
if (fieldName.startsWith('__')) {
context.reportError(
new GraphQLError(
operationName != null
? `Subscription "${operationName}" must not select an introspection top level field.`
: 'Anonymous Subscription must not select an introspection top level field.',
fieldNodes,
),
);
}
}
}
}
},
};
}