GraphQL-Java is a great library, but its syntax is a little bit verbose. This library offers an annotations-based
syntax for GraphQL schema definition.
If you would like to use a tool that creates a graphql spring boot server using graphql-java-annotations, you can view the graphql-spring-annotations library.
The graphql-java-annotations library is able to create GraphQLType objects out of your Java classes.
These GraphQLType objects can be later injected into the graphql-java schema.
graphql-java-annotations also allows you to wire your objects with data fetchers and type resolvers while annotating your fields/types. The result of this process will be a GraphQLCodeRegistry.Builder object that can be later built and injected to the graphql-java schema.
GraphQLAnnotations class
You can create an instance of the GraphQLAnnotations class in order to create the GraphQL types.
Using this object, you will be able to create the GraphQL types.
There are few types that can be generated - a GraphQLObjectType, a GraphQLInterfaceType and a GraphQLDirective.
Then you can use these types in order to create a graphql-java schema.
But, in order to create a graphql-java schema, you need also the GraphQLCodeRegistry, which contains all the data fetchers mapped to their fields (and also type resolvers).
Using the GraphQLAnnotations processor object can be a little bit confusing if you wish to use it to create a GraphQL schema.
So we created a util class to help you create your desired GraphQL schema, in a syntax similiar to the graphql-java syntax.
In order to do so you can use the AnnotationsSchemaCreator.Builder in the following way:
GraphQLSchemaschema = AnnotationsSchemaCreator.newAnnotationsSchema()
.query(Query.class) // to create you query object
.mutation(Mutation.class) // to create your mutation object
.subscription(Subscription.class) // to create your subscription object
.directive(UpperDirective.class) // to create a directive
.additionalType(AdditionalType.class) // to create some additional type and add it to the schema
.typeFunction(CustomType.class) // to add a typefunction
.setAlwaysPrettify(true) // to set the global prettifier of field names (removes get/set/is prefixes from names)
.setRelay(customRelay) // to add a custom relay object
.build();
Of course you can use this builder with only some of the properties, but the query class must be provided.
note - The GraphQLSchema is a graphql-java type.
Continue reading in order to understand how your java classes should look in order to be provided to the annotations schema creator.
Defining Objects
Any regular Java class can be converted to a GraphQL object type. Fields can
be defined with a @GraphQLField (see more on fields below) annotation:
An instance of the type resolver will be created from the specified class. If a getInstance method is present on the
class, it will be used instead of the default constructor.
Defining Unions
To have a union, you must annotate an interface with @GraphQLUnion. In the annotation, you must declare all the
possible types of the union, and a type resolver.
If no type resolver is specified, UnionTypeResolver is used. It follows this algorithm:
The resolver assumes the the DB entity's name is the same as the API entity's name.
If so, it takes the result from the dataFetcher and decides to which
API entity it should be mapped (according to the name).
Example: If you have a Pet union type, and the dataFetcher returns Dog, the typeResolver
will check for each API entity if its name is equal to Dog, and returns if it finds something
NOTE: you can have (but not mandatory) a type resolver with constructor that has Class<?>[] as the first parameter and
ProcessingElementsContainer as the second. the Class<?>[] parameter contains the possibleTypes class
and ProcessingElementsContainer has all sorts of utils (you can check UnionTypeResolver to see how we use it there)
Fields
In addition to specifying a field over a Java class field, a field can be defined over a method:
Note: You need to use -parameters javac option to compile, which makes argument name as the default GraphQL name. Otherwise, you will need to add the @GraphQLName("value") annotation to specify one.
You can also inject DataFetchingEnvironment as an argument, at any position:
In addition, @GraphQLDefaultValue can be used to set a default value to a parameter. Due to limitations of annotations, the default value has to be provided by a class that implements Supplier<Object>:
The DefaultValue class can define a getInstance method that will be called instead of the default constructor.
@GraphQLDeprecate and Java's @Deprecated can be used to specify a deprecated
field or method.
Custom data fetcher
You can specify a custom data fetcher for a field with @GraphQLDataFetcher. The annotation will reference a class name,
which will be used as data fetcher.
An instance of the data fetcher will be created. The args attribute on the annotation can be used to specify a list of
String arguments to pass to the constructor, allowing to reuse the same class on different fields, with different parameter.
The firstArgIsTargetName attribute can also be set on @GraphQLDataFetcher to pass the field name as a single parameter of the constructor.
Assuming you are using @GraphQLDataFetcher this way:
Then the class that extends from DataFetcher.class will get this args to two supported constructors
Or to a constructor that expecting String array that's way (String[] args or String... args) or for a constructor that expecting the same number of args that you send with in the annotation.
You get to choose which implementation you want.
publicclassHelloWorldDataFetcherimplementsDataFetcher<String> {
publicHelloWorldDataFetcher(String[] args){
// Do something with your args
}
// Note that you need to expect the same number of args as you send with in the annotation argspublicHelloWorldDataFetcher(Stringarg1, Stringarg2){
// Do something with your args
}
@OverridepublicStringget(DataFetchingEnvironmentenvironment) {
return"something";
}
}
If no argument is needed and a getInstance method is present, this method will be called instead of the constructor.
Type extensions
Having one single class declaring all fields in a graphQL object type is not always possible, or can lead to huge classes.
Modularizing the schema by defining fields in different classes allows you to split it in smaller chunks of codes.
In IDL, this is usually written by using the extend keyword on top of a type definition. So you have a type defined like this :
type Human {
id: ID!
name: String!
}
It would be possible to extend it later on by using the following syntax :
extend type Human {
homePlanet: String
}
Defining extensions in annotations
This is possible when using annotations by registering "extensions" classes, corresponding to extend clauses, before creating the objects with the GraphQLAnnotationsProcessor.
Extension classes are simple classes, using the same annotations, with an additional @GraphQLTypeExtension on the class itself. The annotation value is required and will be the class that it actually extends.
So the previous schema could be defined by the following classes :
@GraphQLName("Human")
public class Human {
@GraphQLField
public String name() { }
}
@GraphQLTypeExtension(Human.class)
public class HumanExtension {
@GraphQLField
public String homePlanet() { }
}
Classes marked as "extensions" will actually not define a new type, but rather set new fields on the class it extends when it will be created.
All GraphQL annotations can be used on extension classes.
Extensions are registered in GraphQLAnnotations object by using registerTypeExtension. Note that extensions must be registered before the type itself is requested with getObject() :
// Register extensions
graphqlAnnotations.registerTypeExtension(HumanExtension.class);
// Create type
GraphQLObjectType type = processor.getObject(Human.class);
Data fetching with extensions
As opposed to standard annotated classes mapped to GraphQL types, no instance of the extensions are created by default.
In DataFetcher, the source object will still be an instance of the extended class.
It is however possible to provide a constructor taking the extended class as parameter. This constructor will be used to create an instance of the extension class when a field with the default DataFetcher (without @DataFetcher) will be queried.
If no such constructor is provided, the field must either be declared as static or marked as @GraphQLInvokeDetached. Original source object can be found in the DataFetchingEnvironment.
@GraphQLTypeExtension(Human.class)
public class HumanExtension {
public HumanExtension(Human human) {
this.human = human;
}
@GraphQLField
public String homePlanet() {
// get value somehow from human object
}
}
Type Inference
By default, standard GraphQL types (String, Integer, Long, Float, Boolean, Enum, List) will be inferred from Java types. Also, it will respect @GraphQLNonNull with respect to value's nullability
Stream type is also supported and treated as a list.
If you want to register an additional type (for example, UUID), you have to create a new class implementing TypeFunction for it:
graphqlAnnotations.registerType(newUUIDTypeFunction())
// or if not using a static version of GraphQLAnnotations:// new GraphQLAnnotations().registerType(new UUIDTypeFunction())
You can also specify custom type function for any field with @GraphQLType annotation.
Directives
In GraphQL, you can add directives to your schema. Directive is a way of adding some logic to your schema or changing your schema.
For example, we can create a @upper directive, that if we add it to string fields in our schema, they will be transformed to upper cases (its an example, you need to implement it).
Declaring a GraphQLDirective
There are multiple ways to declare a directive in your schema using graphql-java-annotations.
Using a Java Annotation (recommended)
This is the most recommended way of creating a directive, because it is very easy to use later in your schema.
In order to declare a directive using a java annotation, you first have to create the java annotation, and annotate it with special annotations.
For example, we wish to create a directive that adds suffix to graphql fields.
@GraphQLName("suffix")
@GraphQLDescription("this directive adds suffix to a string type")
@GraphQLDirectiveDefinition(wiring = SuffixWiring.class)
@DirectiveLocations({Introspection.DirectiveLocation.FIELD_DEFINITION, Introspection.DirectiveLocation.INTERFACE})
@Retention(RetentionPolicy.RUNTIME)
@interface Suffix {
@GraphQLName("suffixToAdd")
@GraphQLDescription("the suffix to add to your type")
booleansuffixToAdd() defaulttrue;
}
must be annotated with @GraphQLDirectiveDefinition and to supply a wiring class to it (will be explained later)
the name of the directive will be taken from the class name (Suffix) or if annotated with @GraphQLName - from its value
the description is taken from the @GraphQLDescription annotation
must be annotated with @Retention with a RUNTIME policy
must be annotated with @DirectiveLocations in order to specify where we can put this directive on (for example - field definition, interface)
You can see that we also defined a sufixToAdd argument for the directive. We can also use @GraphQLName and @GraphQLDescription annotations in there.
In order to define a default value for the argument, use the default keyword like in the example.
After you created the class, you will be able to create the GraphQLDirective object using the following code:
The name of the directive will be taken from the @GraphQLName annotation (if not specified, the name will be the class's name).
The description of the directive will be taken from the @GraphQLDescription annotation's value.
The valid locations of the directive (locations which the directive can be applied on) will be taken from @DirectiveLocations.
The arguments of the directive will be taken from the fields defined in the class - notice that you can only use primitive types as arguments of a directive.
For example, we defined an isActive field - which is boolean, and its default value is true. That's how the argument of the directive will be defined.
You can also use @GraphQLName and @GraphQLDescription annotations on the field.
After you created the class, you will be able to create the GraphQLDirective object using the following code:
In this example we wrap the data fetcher of the field in order to make the resolved value upper case.
You can also use the field.transform method in order to change some of the field's properties.
This class turns your string field to upper case if the directive argument "isActive" is set to true.
Put this class inside the @GraphQLDirectiveDefinition(wiring = UpperWiring.class) annotation where you declare your directive (see directive declaration section above).
Using the directives
There are 2 ways of using the directives in your graphql types.
请发表评论