-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
QueryTraverser.java
344 lines (309 loc) · 13 KB
/
QueryTraverser.java
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package graphql.analysis;
import graphql.PublicApi;
import graphql.execution.CoercedVariables;
import graphql.execution.RawVariables;
import graphql.execution.ValuesResolver;
import graphql.language.Document;
import graphql.language.FragmentDefinition;
import graphql.language.FragmentSpread;
import graphql.language.Node;
import graphql.language.NodeTraverser;
import graphql.language.NodeUtil;
import graphql.language.OperationDefinition;
import graphql.language.VariableDefinition;
import graphql.schema.GraphQLCompositeType;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static graphql.Assert.assertNotNull;
import static graphql.Assert.assertShouldNeverHappen;
import static java.util.Collections.singletonList;
/**
* Helps to traverse (or reduce) a Document (or parts of it) and tracks at the same time the corresponding Schema types.
* <p>
* This is an important distinction to just traversing the Document without any type information: Each field has a clearly
* defined type. See {@link QueryVisitorFieldEnvironment}.
* <p>
* Furthermore are the built in Directives skip/include automatically evaluated: if parts of the Document should be ignored they will not
* be visited. But this is not a full evaluation of a Query: every fragment will be visited/followed regardless of the type condition.
* <p>
* It also doesn't consider field merging, which means for example {@code { user{firstName} user{firstName}} } will result in four
* visitField calls.
*/
@PublicApi
public class QueryTraverser {
private final Collection<? extends Node> roots;
private final GraphQLSchema schema;
private final Map<String, FragmentDefinition> fragmentsByName;
private CoercedVariables coercedVariables;
private final GraphQLCompositeType rootParentType;
private QueryTraverser(GraphQLSchema schema,
Document document,
String operation,
CoercedVariables coercedVariables) {
this.schema = schema;
NodeUtil.GetOperationResult getOperationResult = NodeUtil.getOperation(document, operation);
this.fragmentsByName = getOperationResult.fragmentsByName;
this.roots = singletonList(getOperationResult.operationDefinition);
this.rootParentType = getRootTypeFromOperation(getOperationResult.operationDefinition);
this.coercedVariables = coercedVariables;
}
private QueryTraverser(GraphQLSchema schema,
Document document,
String operation,
RawVariables rawVariables) {
this.schema = schema;
NodeUtil.GetOperationResult getOperationResult = NodeUtil.getOperation(document, operation);
List<VariableDefinition> variableDefinitions = getOperationResult.operationDefinition.getVariableDefinitions();
this.fragmentsByName = getOperationResult.fragmentsByName;
this.roots = singletonList(getOperationResult.operationDefinition);
this.rootParentType = getRootTypeFromOperation(getOperationResult.operationDefinition);
this.coercedVariables = new ValuesResolver().coerceVariableValues(schema, variableDefinitions, rawVariables);
}
private QueryTraverser(GraphQLSchema schema,
Node root,
GraphQLCompositeType rootParentType,
Map<String, FragmentDefinition> fragmentsByName,
CoercedVariables coercedVariables) {
this.schema = schema;
this.roots = Collections.singleton(root);
this.rootParentType = rootParentType;
this.fragmentsByName = fragmentsByName;
this.coercedVariables = coercedVariables;
}
public Object visitDepthFirst(QueryVisitor queryVisitor) {
return visitImpl(queryVisitor, null);
}
/**
* Visits the Document (or parts of it) in post-order.
*
* @param visitor the query visitor that will be called back
*/
public void visitPostOrder(QueryVisitor visitor) {
visitImpl(visitor, false);
}
/**
* Visits the Document (or parts of it) in pre-order.
*
* @param visitor the query visitor that will be called back
*/
public void visitPreOrder(QueryVisitor visitor) {
visitImpl(visitor, true);
}
/**
* Reduces the fields of a Document (or parts of it) to a single value. The fields are visited in post-order.
*
* @param queryReducer the query reducer
* @param initialValue the initial value to pass to the reducer
* @param <T> the type of reduced value
*
* @return the calculated overall value
*/
@SuppressWarnings("unchecked")
public <T> T reducePostOrder(QueryReducer<T> queryReducer, T initialValue) {
// compiler hack to make acc final and mutable :-)
final Object[] acc = {initialValue};
visitPostOrder(new QueryVisitorStub() {
@Override
public void visitField(QueryVisitorFieldEnvironment env) {
acc[0] = queryReducer.reduceField(env, (T) acc[0]);
}
});
return (T) acc[0];
}
/**
* Reduces the fields of a Document (or parts of it) to a single value. The fields are visited in pre-order.
*
* @param queryReducer the query reducer
* @param initialValue the initial value to pass to the reducer
* @param <T> the type of reduced value
*
* @return the calculated overall value
*/
@SuppressWarnings("unchecked")
public <T> T reducePreOrder(QueryReducer<T> queryReducer, T initialValue) {
// compiler hack to make acc final and mutable :-)
final Object[] acc = {initialValue};
visitPreOrder(new QueryVisitorStub() {
@Override
public void visitField(QueryVisitorFieldEnvironment env) {
acc[0] = queryReducer.reduceField(env, (T) acc[0]);
}
});
return (T) acc[0];
}
private GraphQLObjectType getRootTypeFromOperation(OperationDefinition operationDefinition) {
switch (operationDefinition.getOperation()) {
case MUTATION:
return assertNotNull(schema.getMutationType());
case QUERY:
return assertNotNull(schema.getQueryType());
case SUBSCRIPTION:
return assertNotNull(schema.getSubscriptionType());
default:
return assertShouldNeverHappen();
}
}
private List<Node> childrenOf(Node<?> node) {
if (!(node instanceof FragmentSpread)) {
return node.getChildren();
}
FragmentSpread fragmentSpread = (FragmentSpread) node;
return singletonList(fragmentsByName.get(fragmentSpread.getName()));
}
private Object visitImpl(QueryVisitor visitFieldCallback, Boolean preOrder) {
Map<Class<?>, Object> rootVars = new LinkedHashMap<>();
rootVars.put(QueryTraversalContext.class, new QueryTraversalContext(rootParentType, null, null));
QueryVisitor preOrderCallback;
QueryVisitor postOrderCallback;
if (preOrder == null) {
preOrderCallback = visitFieldCallback;
postOrderCallback = visitFieldCallback;
} else {
QueryVisitor noOp = new QueryVisitorStub();
preOrderCallback = preOrder ? visitFieldCallback : noOp;
postOrderCallback = !preOrder ? visitFieldCallback : noOp;
}
NodeTraverser nodeTraverser = new NodeTraverser(rootVars, this::childrenOf);
NodeVisitorWithTypeTracking nodeVisitorWithTypeTracking = new NodeVisitorWithTypeTracking(preOrderCallback, postOrderCallback, coercedVariables.toMap(), schema, fragmentsByName);
return nodeTraverser.depthFirst(nodeVisitorWithTypeTracking, roots);
}
public static Builder newQueryTraverser() {
return new Builder();
}
@PublicApi
public static class Builder {
private GraphQLSchema schema;
private Document document;
private String operation;
private CoercedVariables coercedVariables = CoercedVariables.emptyVariables();
private RawVariables rawVariables;
private Node root;
private GraphQLCompositeType rootParentType;
private Map<String, FragmentDefinition> fragmentsByName;
/**
* The schema used to identify the types of the query.
*
* @param schema the schema to use
*
* @return this builder
*/
public Builder schema(GraphQLSchema schema) {
this.schema = assertNotNull(schema, () -> "schema can't be null");
return this;
}
/**
* specify the operation if a document is traversed and there
* are more than one operation.
*
* @param operationName the operation name to use
*
* @return this builder
*/
public Builder operationName(String operationName) {
this.operation = operationName;
return this;
}
/**
* document to be used to traverse the whole query.
* If set a {@link Builder#operationName(String)} might be required.
*
* @param document the document to use
*
* @return this builder
*/
public Builder document(Document document) {
this.document = assertNotNull(document, () -> "document can't be null");
return this;
}
/**
* Raw variables used in the query.
*
* @param variables the variables to use
*
* @return this builder
*/
public Builder variables(Map<String, Object> variables) {
assertNotNull(variables, () -> "variables can't be null");
this.rawVariables = RawVariables.of(variables);
return this;
}
/**
* Variables (already coerced) used in the query.
*
* @param coercedVariables the variables to use
*
* @return this builder
*/
public Builder coercedVariables(CoercedVariables coercedVariables) {
assertNotNull(coercedVariables, () -> "coercedVariables can't be null");
this.coercedVariables = coercedVariables;
return this;
}
/**
* Specify the root node for the traversal. Needs to be provided if there is
* no {@link Builder#document(Document)}.
*
* @param root the root node to use
*
* @return this builder
*/
public Builder root(Node root) {
this.root = assertNotNull(root, () -> "root can't be null");
return this;
}
/**
* The type of the parent of the root node. (See {@link Builder#root(Node)}
*
* @param rootParentType the root parent type
*
* @return this builder
*/
public Builder rootParentType(GraphQLCompositeType rootParentType) {
this.rootParentType = assertNotNull(rootParentType, () -> "rootParentType can't be null");
return this;
}
/**
* Fragment by name map. Needs to be provided together with a {@link Builder#root(Node)} and {@link Builder#rootParentType(GraphQLCompositeType)}
*
* @param fragmentsByName the map of fragments
*
* @return this builder
*/
public Builder fragmentsByName(Map<String, FragmentDefinition> fragmentsByName) {
this.fragmentsByName = assertNotNull(fragmentsByName, () -> "fragmentsByName can't be null");
return this;
}
/**
* @return a built {@link QueryTraverser} object
*/
public QueryTraverser build() {
checkState();
if (document != null) {
if (rawVariables != null) {
return new QueryTraverser(schema, document, operation, rawVariables);
}
return new QueryTraverser(schema, document, operation, coercedVariables);
} else {
if (rawVariables != null) {
// When traversing with an arbitrary root, there is no variable definition context available
// Thus, the variables must have already been coerced
// Retaining this builder for backwards compatibility
return new QueryTraverser(schema, root, rootParentType, fragmentsByName, CoercedVariables.of(rawVariables.toMap()));
}
return new QueryTraverser(schema, root, rootParentType, fragmentsByName, coercedVariables);
}
}
private void checkState() {
if (document != null || operation != null) {
if (root != null || rootParentType != null || fragmentsByName != null) {
throw new IllegalStateException("ambiguous builder");
}
}
}
}
}