forked from graphql-java/graphql-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadmeExamples.java
More file actions
520 lines (430 loc) · 18.6 KB
/
Copy pathReadmeExamples.java
File metadata and controls
520 lines (430 loc) · 18.6 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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package readme;
import graphql.ErrorClassification;
import graphql.GraphQLError;
import graphql.GraphqlErrorBuilder;
import graphql.InvalidSyntaxError;
import graphql.Scalars;
import graphql.StarWarsData;
import graphql.TypeResolutionEnvironment;
import graphql.language.Directive;
import graphql.language.FieldDefinition;
import graphql.language.TypeDefinition;
import graphql.schema.Coercing;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import graphql.schema.GraphQLCodeRegistry;
import graphql.schema.GraphQLEnumType;
import graphql.schema.GraphQLInputObjectType;
import graphql.schema.GraphQLInterfaceType;
import graphql.schema.GraphQLList;
import graphql.schema.GraphQLNonNull;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLScalarType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLTypeReference;
import graphql.schema.GraphQLUnionType;
import graphql.schema.StaticDataFetcher;
import graphql.schema.TypeResolver;
import graphql.schema.idl.FieldWiringEnvironment;
import graphql.schema.idl.InterfaceWiringEnvironment;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import graphql.schema.idl.UnionWiringEnvironment;
import graphql.schema.idl.WiringFactory;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import static graphql.GarfieldSchema.Cat;
import static graphql.GarfieldSchema.CatType;
import static graphql.GarfieldSchema.Dog;
import static graphql.GarfieldSchema.DogType;
import static graphql.MutationSchema.mutationType;
import static graphql.Scalars.GraphQLBoolean;
import static graphql.Scalars.GraphQLString;
import static graphql.StarWarsSchema.queryType;
import static graphql.schema.FieldCoordinates.coordinates;
import static graphql.schema.GraphQLArgument.newArgument;
import static graphql.schema.GraphQLCodeRegistry.newCodeRegistry;
import static graphql.schema.GraphQLEnumType.newEnum;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
import static graphql.schema.GraphQLInputObjectField.newInputObjectField;
import static graphql.schema.GraphQLInputObjectType.newInputObject;
import static graphql.schema.GraphQLInterfaceType.newInterface;
import static graphql.schema.GraphQLList.list;
import static graphql.schema.GraphQLNonNull.nonNull;
import static graphql.schema.GraphQLObjectType.newObject;
import static graphql.schema.GraphQLUnionType.newUnionType;
import static graphql.schema.idl.TypeRuntimeWiring.newTypeWiring;
/**
* This class holds readme examples so they stay correct and can be compiled. If this
* does not parse, chances are the readme examples are now wrong.
*
* You should place these examples into the README.next.md and NOT the main README.md. This allows
* 'master' to progress yet shows consumers the released information about the project.
*/
@SuppressWarnings({"unused", "Convert2Lambda", "UnnecessaryLocalVariable", "ConstantConditions", "SameParameterValue", "ClassCanBeStatic"})
public class ReadmeExamples {
public Map<String, Object> getInputFromJSON() {
return new HashMap<>();
}
class Foo {
}
void creatingASchema() {
GraphQLSchema schema = GraphQLSchema.newSchema()
.query(queryType) // must be provided
.mutation(mutationType) // is optional
.build();
GraphQLUnionType.Builder description = newUnionType().description("");
description.definition(null).build();
}
void listsAndNonNullLists() {
GraphQLList.list(GraphQLString); // a list of Strings
GraphQLNonNull.nonNull(GraphQLString); // a non null String
// with static imports it's even shorter
newArgument()
.name("example")
.type(nonNull(list(GraphQLString)));
}
void newType() {
GraphQLObjectType simpsonCharacter = newObject()
.name("SimpsonCharacter")
.description("A Simpson character")
.field(newFieldDefinition()
.name("name")
.description("The name of the character.")
.type(GraphQLString))
.field(newFieldDefinition()
.name("mainCharacter")
.description("One of the main Simpson characters?")
.type(GraphQLBoolean))
.build();
}
void interfaceType() {
GraphQLInterfaceType comicCharacter = newInterface()
.name("ComicCharacter")
.description("A abstract comic character.")
.field(newFieldDefinition()
.name("name")
.description("The name of the character.")
.type(GraphQLString))
.build();
}
void inputTypes() {
GraphQLInputObjectType inputObjectType = newInputObject()
.name("inputObjectType")
.field(newInputObjectField()
.name("field")
.type(GraphQLString))
.build();
}
void enumTypes() {
GraphQLEnumType colorEnum = newEnum()
.name("Color")
.description("Supported colors.")
.value("RED")
.value("GREEN")
.value("BLUE")
.build();
}
void unionType() {
TypeResolver typeResolver = new TypeResolver() {
@Override
public GraphQLObjectType getType(TypeResolutionEnvironment env) {
if (env.getObject() instanceof Cat) {
return CatType;
}
if (env.getObject() instanceof Dog) {
return DogType;
}
return null;
}
};
GraphQLUnionType PetType = newUnionType()
.name("Pet")
.possibleType(CatType)
.possibleType(DogType)
.build();
GraphQLCodeRegistry codeRegistry = newCodeRegistry()
.typeResolver("Pet", typeResolver)
.build();
}
void recursiveTypes() {
GraphQLObjectType person = newObject()
.name("Person")
.field(newFieldDefinition()
.name("friends")
.type(GraphQLList.list(GraphQLTypeReference.typeRef("Person"))))
.build();
}
void dataFetching() {
DataFetcher<Foo> fooDataFetcher = new DataFetcher<Foo>() {
@Override
public Foo get(DataFetchingEnvironment environment) {
// environment.getSource() is the value of the surrounding
// object. In this case described by objectType
Foo value = perhapsFromDatabase(); // Perhaps getting from a DB or whatever
return value;
}
};
GraphQLObjectType objectType = newObject()
.name("ObjectType")
.field(newFieldDefinition()
.name("foo")
.type(GraphQLString)
)
.build();
GraphQLCodeRegistry codeRegistry = newCodeRegistry()
.dataFetcher(
coordinates("ObjectType", "foo"),
fooDataFetcher)
.build();
}
class Review {
}
static class EpisodeInput {
public static EpisodeInput fromMap(Map<String, Object> episodeInput) {
return null;
}
}
static class ReviewInput {
public static ReviewInput fromMap(Map<String, Object> reviewInput) {
return null;
}
}
class ReviewStore {
Review update(EpisodeInput episodeInput, ReviewInput reviewInput) {
return null;
}
}
private ReviewStore reviewStore() {
return new ReviewStore();
}
void mutationExample() {
GraphQLInputObjectType episodeType = newInputObject()
.name("Episode")
.field(newInputObjectField()
.name("episodeNumber")
.type(Scalars.GraphQLInt))
.build();
GraphQLInputObjectType reviewInputType = newInputObject()
.name("ReviewInput")
.field(newInputObjectField()
.name("stars")
.type(Scalars.GraphQLString)
.name("commentary")
.type(Scalars.GraphQLString))
.build();
GraphQLObjectType reviewType = newObject()
.name("Review")
.field(newFieldDefinition()
.name("stars")
.type(GraphQLString))
.field(newFieldDefinition()
.name("commentary")
.type(GraphQLString))
.build();
GraphQLObjectType createReviewForEpisodeMutation = newObject()
.name("CreateReviewForEpisodeMutation")
.field(newFieldDefinition()
.name("createReview")
.type(reviewType)
.argument(newArgument()
.name("episode")
.type(episodeType)
)
.argument(newArgument()
.name("review")
.type(reviewInputType)
)
)
.build();
GraphQLCodeRegistry codeRegistry = newCodeRegistry()
.dataFetcher(
coordinates("CreateReviewForEpisodeMutation", "createReview"),
mutationDataFetcher()
)
.build();
GraphQLSchema schema = GraphQLSchema.newSchema()
.query(queryType)
.mutation(createReviewForEpisodeMutation)
.codeRegistry(codeRegistry)
.build();
}
private DataFetcher mutationDataFetcher() {
return new DataFetcher() {
@Override
public Review get(DataFetchingEnvironment environment) {
//
// The graphql specification dictates that input object arguments MUST
// be maps. You can convert them to POJOs inside the data fetcher if that
// suits your code better
//
// See https://spec.graphql.org/October2021/#sec-Input-Objects
//
Map<String, Object> episodeInputMap = environment.getArgument("episode");
Map<String, Object> reviewInputMap = environment.getArgument("review");
//
// in this case we have type safe Java objects to call our backing code with
//
EpisodeInput episodeInput = EpisodeInput.fromMap(episodeInputMap);
ReviewInput reviewInput = ReviewInput.fromMap(reviewInputMap);
// make a call to your store to mutate your database
Review updatedReview = reviewStore().update(episodeInput, reviewInput);
// this returns a new view of the data
return updatedReview;
}
};
}
private Object context() {
return null;
}
private Foo perhapsFromDatabase() {
return new Foo();
}
void parsedSchemaExample() {
SchemaParser schemaParser = new SchemaParser();
SchemaGenerator schemaGenerator = new SchemaGenerator();
File schemaFile = loadSchema("starWarsSchema.graphqls");
TypeDefinitionRegistry typeRegistry = schemaParser.parse(schemaFile);
RuntimeWiring wiring = buildRuntimeWiring();
GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeRegistry, wiring);
}
void parsedSplitSchemaExample() {
SchemaParser schemaParser = new SchemaParser();
SchemaGenerator schemaGenerator = new SchemaGenerator();
File schemaFile1 = loadSchema("starWarsSchemaPart1.graphqls");
File schemaFile2 = loadSchema("starWarsSchemaPart2.graphqls");
File schemaFile3 = loadSchema("starWarsSchemaPart3.graphqls");
TypeDefinitionRegistry typeRegistry = new TypeDefinitionRegistry();
// each compiled registry is merged into the main registry
typeRegistry.merge(schemaParser.parse(schemaFile1));
typeRegistry.merge(schemaParser.parse(schemaFile2));
typeRegistry.merge(schemaParser.parse(schemaFile3));
GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeRegistry, buildRuntimeWiring());
}
RuntimeWiring buildRuntimeWiring() {
return RuntimeWiring.newRuntimeWiring()
.scalar(CustomScalar)
// this uses builder function lambda syntax
.type("QueryType", typeWiring -> typeWiring
.dataFetcher("hero", new StaticDataFetcher(StarWarsData.getArtoo()))
.dataFetcher("human", StarWarsData.getHumanDataFetcher())
.dataFetcher("droid", StarWarsData.getDroidDataFetcher())
)
.type("Human", typeWiring -> typeWiring
.dataFetcher("friends", StarWarsData.getFriendsDataFetcher())
)
// you can use builder syntax if you don't like the lambda syntax
.type(newTypeWiring("Droid")
.dataFetcher("friends", StarWarsData.getFriendsDataFetcher())
)
// or full builder syntax if that takes your fancy where you call .build()
.type(
newTypeWiring("Character")
.typeResolver(StarWarsData.getCharacterTypeResolver())
.build()
)
.build();
}
RuntimeWiring buildDynamicRuntimeWiring() {
WiringFactory dynamicWiringFactory = new WiringFactory() {
@Override
public boolean providesTypeResolver(InterfaceWiringEnvironment environment) {
return getDirective(environment.getInterfaceTypeDefinition(), "specialMarker") != null;
}
@Override
public boolean providesTypeResolver(UnionWiringEnvironment environment) {
return getDirective(environment.getUnionTypeDefinition(), "specialMarker") != null;
}
@Override
public TypeResolver getTypeResolver(InterfaceWiringEnvironment environment) {
Directive directive = getDirective(environment.getInterfaceTypeDefinition(), "specialMarker");
return createTypeResolver(environment.getInterfaceTypeDefinition(), directive);
}
@Override
public TypeResolver getTypeResolver(UnionWiringEnvironment environment) {
Directive directive = getDirective(environment.getUnionTypeDefinition(), "specialMarker");
return createTypeResolver(environment.getUnionTypeDefinition(), directive);
}
@Override
public boolean providesDataFetcher(FieldWiringEnvironment environment) {
return getDirective(environment.getFieldDefinition(), "dataFetcher") != null;
}
@Override
public DataFetcher getDataFetcher(FieldWiringEnvironment environment) {
Directive directive = getDirective(environment.getFieldDefinition(), "dataFetcher");
return createDataFetcher(environment.getFieldDefinition(), directive);
}
};
return RuntimeWiring.newRuntimeWiring()
.wiringFactory(dynamicWiringFactory).build();
}
class Wizard {
}
class Witch {
}
private void typeResolverExample() {
TypeResolver typeResolver = new TypeResolver() {
@Override
public GraphQLObjectType getType(TypeResolutionEnvironment env) {
Object javaObject = env.getObject();
if (javaObject instanceof Wizard) {
return (GraphQLObjectType) env.getSchema().getType("WizardType");
} else if (javaObject instanceof Witch) {
return (GraphQLObjectType) env.getSchema().getType("WitchType");
} else {
return (GraphQLObjectType) env.getSchema().getType("NecromancerType");
}
}
};
}
static class SpecialError extends InvalidSyntaxError {
public SpecialError(SpecialErrorBuilder builder) {
super(builder.getLocations(), builder.getMessage());
}
}
static class SpecialErrorBuilder extends GraphqlErrorBuilder<SpecialErrorBuilder> {
@Override
public SpecialError build() {
return new SpecialError(this);
}
}
private void errorBuilderExample() {
GraphQLError err = GraphQLError.newError()
.message("direct")
.errorType(ErrorClassification.errorClassification("customClassification"))
.build();
SpecialError specialErr = new SpecialErrorBuilder().message("special").build();
}
private DataFetcher createDataFetcher(FieldDefinition definition, Directive directive) {
throw new UnsupportedOperationException("Not implemented");
}
private TypeResolver createTypeResolver(TypeDefinition definition, Directive directive) {
throw new UnsupportedOperationException("Not implemented");
}
private Directive getDirective(TypeDefinition definition, String type) {
throw new UnsupportedOperationException("Not implemented");
}
private Directive getDirective(FieldDefinition fieldDefintion, String type) {
throw new UnsupportedOperationException("Not implemented");
}
public static GraphQLScalarType CustomScalar = GraphQLScalarType.newScalar().name("Custom").description("Custom Scalar").coercing(new Coercing<Integer, Integer>() {
@Override
public Integer serialize(Object input) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public Integer parseValue(Object input) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public Integer parseLiteral(Object input) {
throw new UnsupportedOperationException("Not implemented");
}
}).build();
private File loadSchema(String s) {
return null;
}
}