5

我在尝试构建相互依赖的类型时遇到了障碍,这里是代码:

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();
    }

}

它不可能实例化这个类,因为我得到了这个例外

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)

显然 classType 在 createStudentType() 引用它时还没有实例化。我如何解决这个问题?

4

2 回答 2

7

GraphQLTypeReference 确实是答案。这应该这样做:

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();
    }

}
于 2016-07-07T11:50:39.250 回答
1

你试过用new GraphQLTypeReference("ForwardType")吗?我说的是这个https://github.com/graphql-java/graphql-java#recursive-type-references

于 2016-07-07T10:23:30.140 回答