-
Notifications
You must be signed in to change notification settings - Fork 117
/
SelectionSet.java
394 lines (357 loc) · 15.2 KB
/
SelectionSet.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amplifyframework.api.aws;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.core.util.ObjectsCompat;
import com.amplifyframework.AmplifyException;
import com.amplifyframework.api.graphql.Operation;
import com.amplifyframework.api.graphql.QueryType;
import com.amplifyframework.core.model.AuthRule;
import com.amplifyframework.core.model.AuthStrategy;
import com.amplifyframework.core.model.Model;
import com.amplifyframework.core.model.ModelAssociation;
import com.amplifyframework.core.model.ModelField;
import com.amplifyframework.core.model.ModelSchema;
import com.amplifyframework.core.model.ModelSchemaRegistry;
import com.amplifyframework.core.model.SerializedModel;
import com.amplifyframework.core.model.types.JavaFieldType;
import com.amplifyframework.util.Empty;
import com.amplifyframework.util.FieldFinder;
import com.amplifyframework.util.Wrap;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Class representing a node of a SelectionSet for use in a GraphQLDocument.
* A root SelectionSet node will have a null value.
*/
public final class SelectionSet {
private static final String INDENT = " ";
private final String value;
private final Set<SelectionSet> nodes;
/**
* Copy constructor.
* @param selectionSet node to copy
*/
@SuppressWarnings("CopyConstructorMissesField") // It is cloned, by recursion
public SelectionSet(SelectionSet selectionSet) {
this(selectionSet.value, new HashSet<>(selectionSet.nodes));
}
/**
* Constructor for a leaf node (no children).
* @param value String value of the field.
*/
public SelectionSet(String value) {
this(value, Collections.emptySet());
}
/**
* Default constructor.
* @param value String value of the field
* @param nodes Set of child nodes
*/
public SelectionSet(String value, @NonNull Set<SelectionSet> nodes) {
this.value = value;
this.nodes = Objects.requireNonNull(nodes);
}
/**
* Returns child nodes.
* @return child nodes
*/
@NonNull
public Set<SelectionSet> getNodes() {
return nodes;
}
/**
* Generate the String value of the SelectionSet used in the GraphQL query document, with no margin.
*
* Sample return value:
* items {
* foo
* bar
* modelName {
* foo
* bar
* }
* }
* nextToken
*
* @return String value of the selection set for a GraphQL query document.
*/
@Override
public String toString() {
return toString("");
}
/**
* Generates the String value of the SelectionSet for a GraphQL query document.
* @param margin a margin with which to prefix each field of the selection set.
* @return String value of the SelectionSet for a GraphQL query document.
*/
public String toString(String margin) {
List<String> fieldsList = new ArrayList<>();
StringBuilder builder = new StringBuilder();
if (value != null) {
builder.append(value);
}
if (!Empty.check(nodes)) {
for (SelectionSet node : nodes) {
fieldsList.add(node.toString(margin + INDENT));
}
Collections.sort(fieldsList);
String delimiter = "\n" + margin + INDENT;
builder.append(Wrap.inPrettyBraces(TextUtils.join(delimiter, fieldsList), margin, INDENT));
}
return builder.toString();
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
SelectionSet selectionSet = (SelectionSet) object;
return ObjectsCompat.equals(value, selectionSet.value);
}
@Override
public int hashCode() {
return ObjectsCompat.hash(value);
}
/**
* Create a new SelectionSet builder.
* @return a new SelectionSet builder.
*/
public static SelectionSet.Builder builder() {
return new Builder();
}
/**
* Factory class for creating and serializing a selection set within a GraphQL document.
*/
static final class Builder {
private Class<? extends Model> modelClass;
private Operation operation;
private GraphQLRequestOptions requestOptions;
private ModelSchema modelSchema;
Builder() { }
public Builder modelClass(@NonNull Class<? extends Model> modelClass) {
this.modelClass = Objects.requireNonNull(modelClass);
return Builder.this;
}
public Builder modelSchema(@NonNull ModelSchema modelSchema) {
this.modelSchema = Objects.requireNonNull(modelSchema);
return Builder.this;
}
public Builder operation(@NonNull Operation operation) {
this.operation = Objects.requireNonNull(operation);
return Builder.this;
}
public Builder requestOptions(@NonNull GraphQLRequestOptions requestOptions) {
this.requestOptions = Objects.requireNonNull(requestOptions);
return Builder.this;
}
/**
* Builds the SelectionSet containing all of the fields of the provided model class.
* @return selection set
* @throws AmplifyException if a ModelSchema cannot be created from the provided model class.
*/
public SelectionSet build() throws AmplifyException {
if (this.modelClass == null && this.modelSchema == null) {
throw new AmplifyException("Both modelClass and modelSchema cannot be null",
"Provide either a modelClass or a modelSchema to build the selection set");
}
Objects.requireNonNull(this.operation);
SelectionSet node = new SelectionSet(null,
SerializedModel.class == modelClass
? getModelFields(modelSchema, requestOptions.maxDepth())
: getModelFields(modelClass, requestOptions.maxDepth()));
if (QueryType.LIST.equals(operation) || QueryType.SYNC.equals(operation)) {
node = wrapPagination(node);
}
return node;
}
/**
* Expects a {@link SelectionSet} containing {@link Model} fields as nodes, and returns a new root node with two
* children:
* - "items" with nodes being the children of the provided node.
* - "nextToken"
*
* @param node a root node, with a value of null, and pagination fields
* @return A selection set
*/
private SelectionSet wrapPagination(SelectionSet node) {
return new SelectionSet(null, wrapPagination(node.getNodes()));
}
private Set<SelectionSet> wrapPagination(Set<SelectionSet> nodes) {
Set<SelectionSet> paginatedSet = new HashSet<>();
paginatedSet.add(new SelectionSet(requestOptions.listField(), nodes));
for (String metaField : requestOptions.paginationFields()) {
paginatedSet.add(new SelectionSet(metaField));
}
return paginatedSet;
}
/**
* Gets a selection set for the given class.
* TODO: this is mostly duplicative of {@link #getModelFields(ModelSchema, int)}.
* Long-term, we want to remove this current method and rely only on the ModelSchema-based
* version.
* @param clazz Class from which to build selection set
* @param depth Number of children deep to explore
* @return Selection Set
* @throws AmplifyException On faiulre to build selection set
*/
@SuppressWarnings("unchecked") // Cast to Class<Model>
private Set<SelectionSet> getModelFields(Class<? extends Model> clazz, int depth)
throws AmplifyException {
if (depth < 0) {
return new HashSet<>();
}
Set<SelectionSet> result = new HashSet<>();
if (depth == 0 && LeafSerializationBehavior.JUST_ID.equals(requestOptions.leafSerializationBehavior())) {
result.add(new SelectionSet("id"));
return result;
}
ModelSchema schema = ModelSchema.fromModelClass(clazz);
for (Field field : FieldFinder.findModelFieldsIn(clazz)) {
String fieldName = field.getName();
if (schema.getAssociations().containsKey(fieldName)) {
if (List.class.isAssignableFrom(field.getType())) {
if (depth >= 1) {
ParameterizedType listType = (ParameterizedType) field.getGenericType();
Class<Model> listTypeClass = (Class<Model>) listType.getActualTypeArguments()[0];
Set<SelectionSet> fields = wrapPagination(getModelFields(listTypeClass, depth - 1));
result.add(new SelectionSet(fieldName, fields));
}
} else if (depth >= 1) {
Set<SelectionSet> fields = getModelFields((Class<Model>) field.getType(), depth - 1);
result.add(new SelectionSet(fieldName, fields));
}
} else if (isCustomType(field)) {
result.add(new SelectionSet(fieldName, getNestedCustomTypeFields(getClassForField(field))));
} else {
result.add(new SelectionSet(fieldName));
}
for (AuthRule authRule : schema.getAuthRules()) {
if (AuthStrategy.OWNER.equals(authRule.getAuthStrategy())) {
result.add(new SelectionSet(authRule.getOwnerFieldOrDefault()));
break;
}
}
}
for (String fieldName : requestOptions.modelMetaFields()) {
result.add(new SelectionSet(fieldName));
}
return result;
}
/**
* We handle customType fields differently as DEPTH does not apply here.
* @param clazz class we wish to build selection set for
* @return A set of selection sets
*/
private Set<SelectionSet> getNestedCustomTypeFields(Class<?> clazz) {
Set<SelectionSet> result = new HashSet<>();
for (Field field : FieldFinder.findNonTransientFieldsIn(clazz)) {
String fieldName = field.getName();
if (isCustomType(field)) {
result.add(new SelectionSet(fieldName, getNestedCustomTypeFields(getClassForField(field))));
} else {
result.add(new SelectionSet(fieldName));
}
}
return result;
}
/**
* Helper to determine if field is a custom type. If custom types we need to build nested selection set.
* @param field field we wish to check
* @return True if the field is of a custom type
*/
private static boolean isCustomType(@NonNull Field field) {
Class<?> cls = getClassForField(field);
if (Model.class.isAssignableFrom(cls) || Enum.class.isAssignableFrom(cls)) {
return false;
}
try {
JavaFieldType.from(cls);
return false;
} catch (IllegalArgumentException exception) {
// if we get here then field is a custom type
return true;
}
}
/**
* Get the class of a field. If field is a collection, it returns the Generic type
* @return The class of the field
*/
static Class<?> getClassForField(Field field) {
Class<?> typeClass;
if (Collection.class.isAssignableFrom(field.getType())) {
ParameterizedType listType = (ParameterizedType) field.getGenericType();
typeClass = (Class<?>) listType.getActualTypeArguments()[0];
} else {
typeClass = field.getType();
}
return typeClass;
}
// TODO: this method is tech debt. We added it to support usage of the library from Flutter.
// This version of the method needs to be unified with getModelFields(Class<? extends Model> clazz, int depth).
private Set<SelectionSet> getModelFields(ModelSchema modelSchema, int depth) {
if (depth < 0) {
return new HashSet<>();
}
Set<SelectionSet> result = new HashSet<>();
if (depth == 0 && LeafSerializationBehavior.JUST_ID.equals(requestOptions.leafSerializationBehavior())) {
result.add(new SelectionSet("id"));
return result;
}
for (Map.Entry<String, ModelField> entry : modelSchema.getFields().entrySet()) {
String fieldName = entry.getKey();
ModelAssociation association = modelSchema.getAssociations().get(fieldName);
if (association != null) {
if (depth >= 1) {
String associatedModelName = association.getAssociatedType();
ModelSchema associateModelSchema = ModelSchemaRegistry.instance()
.getModelSchemaForModelClass(associatedModelName);
Set<SelectionSet> fields;
if (entry.getValue().isArray()) { // If modelField is an Array
fields = wrapPagination(getModelFields(associateModelSchema, depth - 1));
} else {
fields = getModelFields(associateModelSchema, depth - 1);
}
result.add(new SelectionSet(fieldName, fields));
}
} else {
result.add(new SelectionSet(fieldName));
}
for (AuthRule authRule : modelSchema.getAuthRules()) {
if (AuthStrategy.OWNER.equals(authRule.getAuthStrategy())) {
result.add(new SelectionSet(authRule.getOwnerFieldOrDefault()));
break;
}
}
}
for (String fieldName : requestOptions.modelMetaFields()) {
result.add(new SelectionSet(fieldName));
}
return result;
}
}
}