forked from graphql-java/graphql-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DeepDataFetchers.java
72 lines (61 loc) · 1.98 KB
/
DeepDataFetchers.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
package graphql.execution.instrumentation.dataloader;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import graphql.schema.DataFetcher;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLTypeReference;
public class DeepDataFetchers {
private static <T> CompletableFuture<T> supplyAsyncWithSleep(Supplier<T> supplier) {
Supplier<T> sleepSome = sleepSome(supplier);
return CompletableFuture.supplyAsync(sleepSome);
}
private static <T> Supplier<T> sleepSome(Supplier<T> supplier) {
return () -> {
try {
Thread.sleep(10L);
return supplier.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
public GraphQLSchema schema() {
DataFetcher<CompletableFuture<HashMap<String, Object>>> slowFetcher = environment ->
supplyAsyncWithSleep(HashMap::new);
GraphQLFieldDefinition selfField = GraphQLFieldDefinition.newFieldDefinition()
.name("self")
.type(GraphQLTypeReference.typeRef("Query"))
.dataFetcher(slowFetcher)
.build();
GraphQLObjectType query = GraphQLObjectType.newObject()
.name("Query")
.field(selfField)
.build();
return GraphQLSchema.newSchema().query(query).build();
}
public String buildQuery(Integer depth) {
StringBuilder sb = new StringBuilder();
sb.append("query {");
for (Integer i = 0; i < depth; i++) {
sb.append("self {");
}
sb.append("__typename");
for (Integer i = 0; i < depth; i++) {
sb.append("}");
}
sb.append("}");
return sb.toString();
}
public HashMap<String, Object> buildResponse(Integer depth) {
HashMap<String, Object> level = new HashMap<>();
if (depth == 0) {
level.put("__typename", "Query");
} else {
level.put("self", buildResponse(depth - 1));
}
return level;
}
}