forked from graphql-java/graphql-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecutionExamples.java
More file actions
271 lines (209 loc) · 8.93 KB
/
Copy pathExecutionExamples.java
File metadata and controls
271 lines (209 loc) · 8.93 KB
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
package readme;
import graphql.ErrorType;
import graphql.ExecutionInput;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.GraphQLError;
import graphql.StarWarsSchema;
import graphql.execution.AsyncExecutionStrategy;
import graphql.execution.AsyncSerialExecutionStrategy;
import graphql.execution.DataFetcherExceptionHandler;
import graphql.execution.DataFetcherExceptionHandlerParameters;
import graphql.execution.ExecutionStrategy;
import graphql.execution.ExecutorServiceExecutionStrategy;
import graphql.language.SourceLocation;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLFieldsContainer;
import graphql.schema.GraphQLSchema;
import graphql.schema.visibility.BlockedFields;
import graphql.schema.visibility.GraphqlFieldVisibility;
import graphql.schema.visibility.NoIntrospectionGraphqlFieldVisibility;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static graphql.StarWarsSchema.queryType;
@SuppressWarnings({"unused", "UnnecessaryLocalVariable", "Convert2Lambda"})
public class ExecutionExamples {
public static void main(String[] args) throws Exception {
new ExecutionExamples().simpleQueryExecution();
}
private void simpleQueryExecution() throws Exception {
GraphQLSchema schema = GraphQLSchema.newSchema()
.query(queryType)
.build();
GraphQL graphQL = GraphQL.newGraphQL(schema)
.build();
ExecutionInput executionInput = ExecutionInput.newExecutionInput().query("query { hero { name } }")
.build();
ExecutionResult executionResult = graphQL.execute(executionInput);
Object data = executionResult.getData();
List<GraphQLError> errors = executionResult.getErrors();
}
@SuppressWarnings("Convert2MethodRef")
private void simpleAsyncQueryExecution() throws Exception {
GraphQL graphQL = buildSchema();
ExecutionInput executionInput = ExecutionInput.newExecutionInput().query("query { hero { name } }")
.build();
CompletableFuture<ExecutionResult> promise = graphQL.executeAsync(executionInput);
promise.thenAccept(executionResult -> {
// here you might send back the results as JSON over HTTP
encodeResultToJsonAndSendResponse(executionResult);
});
promise.join();
}
private GraphQL graphQL = buildSchema();
private ExecutionInput executionInput = ExecutionInput.newExecutionInput().query("query { hero { name } }")
.build();
private void equivalentSerialAndAsyncQueryExecution() throws Exception {
ExecutionResult executionResult = graphQL.execute(executionInput);
// the above is equivalent to the following code (in long hand)
CompletableFuture<ExecutionResult> promise = graphQL.executeAsync(executionInput);
ExecutionResult executionResult2 = promise.join();
}
@SuppressWarnings("Convert2Lambda")
private void simpleDataFetcher() {
DataFetcher userDataFetcher = new DataFetcher() {
@Override
public Object get(DataFetchingEnvironment environment) {
return fetchUserFromDatabase(environment.getArgument("userId"));
}
};
}
@SuppressWarnings({"Convert2Lambda", "CodeBlock2Expr"})
private void asyncDataFetcher() {
DataFetcher userDataFetcher = new DataFetcher() {
@Override
public Object get(DataFetchingEnvironment environment) {
CompletableFuture<User> userPromise = CompletableFuture.supplyAsync(
() -> {
return fetchUserFromDatabase(environment.getArgument("userId"));
});
return userPromise;
}
};
}
private void succinctAsyncDataFetcher() {
DataFetcher userDataFetcher = environment -> CompletableFuture.supplyAsync(
() -> fetchUserFromDatabase(environment.getArgument("userId")));
}
private void wireInExecutionStrategies() {
GraphQL.newGraphQL(schema)
.queryExecutionStrategy(new AsyncExecutionStrategy())
.mutationExecutionStrategy(new AsyncSerialExecutionStrategy())
.build();
}
private void exampleExecutorServiceExecutionStrategy() {
ExecutorService executorService = new ThreadPoolExecutor(
2, /* core pool size 2 thread */
2, /* max pool size 2 thread */
30, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(),
new ThreadPoolExecutor.CallerRunsPolicy());
GraphQL graphQL = GraphQL.newGraphQL(StarWarsSchema.starWarsSchema)
.queryExecutionStrategy(new ExecutorServiceExecutionStrategy(executorService))
.mutationExecutionStrategy(new AsyncSerialExecutionStrategy())
.build();
}
private void exceptionHandler() {
DataFetcherExceptionHandler handler = new DataFetcherExceptionHandler() {
@Override
public void accept(DataFetcherExceptionHandlerParameters handlerParameters) {
//
// do your custom handling here. The parameters have all you need
}
};
ExecutionStrategy executionStrategy = new AsyncExecutionStrategy(handler);
}
private void blockedFields() {
GraphqlFieldVisibility blockedFields = BlockedFields.newBlock()
.addPattern("Character.id")
.addPattern("Droid.appearsIn")
.addPattern(".*\\.hero") // it uses regular expressions
.build();
GraphQLSchema schema = GraphQLSchema.newSchema()
.query(StarWarsSchema.queryType)
.fieldVisibility(blockedFields)
.build();
}
private void noIntrospection() {
GraphQLSchema schema = GraphQLSchema.newSchema()
.query(StarWarsSchema.queryType)
.fieldVisibility(NoIntrospectionGraphqlFieldVisibility.NO_INTROSPECTION_FIELD_VISIBILITY)
.build();
}
class YourUserAccessService {
public boolean isAdminUser() {
return false;
}
}
class CustomFieldVisibility implements GraphqlFieldVisibility {
final YourUserAccessService userAccessService;
CustomFieldVisibility(YourUserAccessService userAccessService) {
this.userAccessService = userAccessService;
}
@Override
public List<GraphQLFieldDefinition> getFieldDefinitions(GraphQLFieldsContainer fieldsContainer) {
if ("AdminType".equals(fieldsContainer.getName())) {
if (!userAccessService.isAdminUser()) {
return Collections.emptyList();
}
}
return fieldsContainer.getFieldDefinitions();
}
@Override
public GraphQLFieldDefinition getFieldDefinition(GraphQLFieldsContainer fieldsContainer, String fieldName) {
if ("AdminType".equals(fieldsContainer.getName())) {
if (!userAccessService.isAdminUser()) {
return null;
}
}
return fieldsContainer.getFieldDefinition(fieldName);
}
}
private void sendAsJson(Map<String, Object> toSpecificationResult) {
}
public void toSpec() throws Exception {
ExecutionResult executionResult = graphQL.execute(executionInput);
Map<String, Object> toSpecificationResult = executionResult.toSpecification();
sendAsJson(toSpecificationResult);
}
class CustomRuntimeException extends RuntimeException implements GraphQLError {
@Override
public Map<String, Object> getExtensions() {
Map<String, Object> customAttributes = new LinkedHashMap<>();
customAttributes.put("foo", "bar");
customAttributes.put("fizz", "whizz");
return customAttributes;
}
@Override
public List<SourceLocation> getLocations() {
return null;
}
@Override
public ErrorType getErrorType() {
return ErrorType.DataFetchingException;
}
}
private class User {
}
private <U> U fetchUserFromDatabase(Object userId) {
return null;
}
private void encodeResultToJsonAndSendResponse(ExecutionResult executionResult) {
}
private GraphQLSchema schema = GraphQLSchema.newSchema()
.query(queryType)
.build();
private GraphQL buildSchema() {
return GraphQL.newGraphQL(schema)
.build();
}
}