i've hit a brick wall while trying to construct types that depend on each other, here is the code:
import graphql.schema.GraphQLObjectType;
import static graphql.schema.GraphQLObjectType.newObject;
import static graphql.Scalars.*;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLList;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
public class GraphQLTypes {
private GraphQLObjectType studentType;
private GraphQLObjectType classType;
public GraphQLTypes() {
createStudentType();
createClassType();
}
void createStudentType() {
studentType = newObject().name("Student")
.field(newFieldDefinition().name("name").type(GraphQLString).build())
.field(newFieldDefinition().name("currentClass").type(classType).build())
.build();
}
void createClassType() {
classType = newObject().name("Class")
.field(newFieldDefinition().name("name").type(GraphQLString).build())
.field(newFieldDefinition().name("students").type(new GraphQLList(studentType)).build())
.build();
}
}
its impossible to intantiate this class, as i get this exception
Caused by: graphql.AssertException: type can't be null
at graphql.Assert.assertNotNull(Assert.java:10)
at graphql.schema.GraphQLFieldDefinition.<init>(GraphQLFieldDefinition.java:23)
at graphql.schema.GraphQLFieldDefinition$Builder.build(GraphQLFieldDefinition.java:152)
at graphql_types.GraphQLTypes.createStudentType(GraphQLTypes.java:26)
at graphql_types.GraphQLTypes.<init>(GraphQLTypes.java:19)
obviously classType is not yet intantiated at the point createStudentType() is referencing it. How to i get around this problem?
GraphQLTypeReference is the answer indeed. This should do it:
import graphql.schema.GraphQLList;
import graphql.schema.GraphQLObjectType;
import graphql.schema.GraphQLTypeReference;
import static graphql.Scalars.GraphQLString;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
import static graphql.schema.GraphQLObjectType.newObject;
public class GraphQLTypes {
private GraphQLObjectType studentType;
private GraphQLObjectType classType;
public GraphQLTypes() {
createStudentType();
createClassType();
}
void createStudentType() {
studentType = newObject().name("Student")
.field(newFieldDefinition().name("name").type(GraphQLString).build())
.field(newFieldDefinition().name("currentClass").type(new GraphQLTypeReference("Class")).build())
.build();
}
void createClassType() {
classType = newObject().name("Class")
.field(newFieldDefinition().name("name").type(GraphQLString).build())
.field(newFieldDefinition().name("students").type(new GraphQLList(studentType)).build())
.build();
}
}
Did you try to use new GraphQLTypeReference("ForwardType")
? I'm talking about this one https://github.com/graphql-java/graphql-java#recursive-type-references
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With