用于 Java 的 GraphQL 注解
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.
(Gradle syntax)
dependencies {
compile "io.github.graphql-java:graphql-java-annotations:24.3"
}(Maven syntax)
io.github.graphql-java
graphql-java-annotations
24.3
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.
You can create an instance of the GraphQLAnnotations class in order to create the GraphQL types.
GraphQLAnnotations graphqlAnnotations = new GraphQLAnnotations();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.
GraphQLObjectType query = graphqlAnnotations.object(Query.class);
GraphQLDirective upperDirective = graphqlAnnotations.directive(UpperDirective.class);
GraphQLInterfaceType myInterface = graphqlAnnotations.generateInterface(MyInterface.class); 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).
You can obtain the code registry this way:
graphqlAnnotations.getContainer().getCodeRegistryBuilder().build();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:
…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.
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:
public class SomeObject {
@GraphQLField
public String field;
}
// ...
GraphQLAnnotations graphQLAnnotations = new GraphQLAnnotations();
GraphQLObjectType object = graphQLAnnotations.object(SomeObject.class);This is very similar to defining objects, with the addition of type resolver :
@GraphQLTypeResolver(MyTypeResolver.class)
public interface SomeInterface {
@GraphQLField
String field();
}
public class MyTypeResolver implements TypeResolver {
GraphQLObjectType getType(TypeResolutionEnvironment env) { ... }
}
// ...
GraphQLAnnotations graphQLAnnotations = new GraphQLAnnotations();
GraphQLInterfaceType object = graphQLAnnotations.generateInterface(SomeInterface.class);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.
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
@GraphQLUnion(possibleTypes={Dog.class, Cat.class})
public interface Pet {}and an example with custom TypeResovler:
@GraphQLUnion(possibleTypes={DogApi.class, Cat.class}, typeResolver = PetTypeResolver.class)
public interface Pet {}
public class PetTypeResolver implements TypeResolver {
@Override
GraphQLObjectType getType(TypeResolutionEnvironment env) {
Object obj = env.getObject();
if(obj instanceof DogDB) {
return (GraphQLObjectType) env.getSchema().getType("DogApi");
}
else {
return (GraphQLObjectType) env.getSchema().getType("Cat");
}
}
}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)
In addition to specifying a field over a Java class field, a field can be defined over a method:
public class SomeObject {
@GraphQLField
public String field() {
return "field";
}
}Or a method with arguments:
public class SomeObject {
@GraphQLField
public String field(String value) {
return value;
}
}Note: You need to use
-parametersjavac 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:
public class SomeObject {
@GraphQLField
public String field(DataFetchingEnvironment env, String value) {
return value;
}
}Additionally, @GraphQLName can be used to override field name. You can use @GraphQLDescription to set a description.
These can also be used for field parameters:
public String field(@GraphQLName("val") String value) {
return value;
}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:
public static class DefaultValue implements Supplier {
@Override
public Object get() {
return "default";
}
}
@GraphQLField
public String field(@GraphQLDefaultValue(DefaultValue.class) String value) {
return value;
}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.
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:
@GraphQLField
@GraphQLDataFetcher(value = HelloWorldDataFetcher.class, args = { "arg1", "arg2" })
public String getHelloWorld(){
return null;
}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.
public class HelloWorldDataFetcher implements DataFetcher {
public HelloWorldDataFetcher(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 args
public HelloWorldDataFetcher(String arg1, String arg2){
// Do something with your args
}
@Override
public String get(DataFetchingEnvironment environment) {
return "something";
}
}If no argument is needed and a getInstance method is present, this method will be called instead of the constructor.
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
}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);
As opposed to standard annotated classes mapped
暂无开放 Issues,或尚未同步最近议题。