gpt4 book ai didi

java - graphql-java 循环类型依赖

转载 作者:搜寻专家 更新时间:2023-11-01 01:50:09 25 4
gpt4 key购买 nike

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

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)

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

最佳答案

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

}

关于java - graphql-java 循环类型依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38240599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com