图形ql+;Java-如何筛选子字段?
我在我的Spring应用程序中使用了with(看起来非常有限,看起来不再维护了),我正在努力处理子字段 我想使用GraphQL访问两个类图形ql+;Java-如何筛选子字段?,java,annotations,graphql,graphql-java,Java,Annotations,Graphql,Graphql Java,我在我的Spring应用程序中使用了with(看起来非常有限,看起来不再维护了),我正在努力处理子字段 我想使用GraphQL访问两个类A和B,它们是: class A { @GraphQLField Integer id; @GraphQLField String name; @GraphQLField List<B> listOfB; } class B { @GraphQLField Integer id;
A
和B
,它们是:
class A {
@GraphQLField
Integer id;
@GraphQLField
String name;
@GraphQLField
List<B> listOfB;
}
class B {
@GraphQLField
Integer id;
@GraphQLField
String code;
}
我可以通过以下请求成功筛选a
:
{
a(id:5)
{
id,
name,
listOfB
{
code
}
}
}
但是,当我尝试在列表B
上进行筛选时,例如使用take
仅选择X条记录,我遇到了类型为UnknownArgument:Unknown参数take的错误验证错误:
{
a(id:5)
{
id,
name,
listOfB(take:3)
{
code
}
}
}
我理解错误的含义,因为我没有为A
上的listOfB
字段声明任何可能的参数,但我不知道如何使用graphql java注释来实现它
我使用类a
中的以下代码为listOfB
tho添加了一个特定的DataFetcher
:
@GraphQLDataFetcher(BDataFetcher.class)
private List<B> listOfB;
@GraphQLDataFetcher(BDataFetcher.class)
私人名单b;
当我检索listOfB
时,它确实被调用了
在使用graphqljava注释时,您知道如何向字段添加参数吗?如果没有,是否有解决办法
定义没有注释的模式并使用graphql-java
的“经典”方式不是一个选项,因为我的模式非常庞大:/
谢谢:)这不是我最终使用的解决方案,因为它不符合我的设计,但以下是您可以做的:
public class MyClass
{
@GraphQLField
private Integer id;
private List<String> items;
@GraphQLField
public List<String> items(DataFetchingEnvironment environment, @GraphQLName("take") Integer take, @GraphQLName("after") Integer after)
{
List<String> items = ((MyClass) environment.getSource()).getItems();
Integer fromIndex = 0;
Integer toIndex = items.size();
if (after != null)
fromIndex = after + 1;
if (take != null)
toIndex = fromIndex + take;
return items.subList(fromIndex, toIndex);
}
}
这将使参数take
和after
成为MyClassDataFetcher.get()
方法中的DataFetchingEnvironment
之后的参数,因此您有一个未调用的空方法,但参数仍然传递给DataFetcher
同样,它并不理想,因为我怀疑它的用途,但它是使用数据获取程序的唯一方法,我知道它带有参数
现在,我没有使用这两个解决方案中的任何一个,我最终完全放弃了graphql注释
,并开发了自己的解决方案,使用自定义注释可以自动构建模式(抱歉,不会公开发布)
我不建议使用graphql注释
,除非它们对所有用例都有适当的文档。我强烈建议您再次查看这个库,因为它现在又回来了
维护,自述文件非常清晰
关于你的问题:
您应该使字段listOfB
如下所示:
@GraphQLField
@GraphQLDataFetcher(ListOfBFetcher.class)
List<B> listOfB(int take){return null};
您是否尝试将@GraphQLField与@GraphQLDataFetcher一起添加到listOfB字段中?我在这里做了一些测试并成功了。哦,是的,我很抱歉,它仍然是一个带有数据获取程序的GraphQLField
。但我还是犯了同样的错误。我通过将listOfB
定义为一个方法而不是一个字段来实现它,但它最终变得非常乏味,所以我目前正在编写自定义注释,只需在任何字段上添加一个@graphqlanotation
注释,就可以对其进行自动筛选。我有类似的问题,您能帮助我吗?很好,谢谢你的更新。我不再使用GraphQL处理这个项目,虽然现在它没有什么用处,但是如果我再次使用GraphQL,我会确保检查更新:)到今天为止,这个库再次得到维护,并记录在案。如果您不理解某些内容,请打开一个问题,我们将帮助您
public class MyClass
{
@GraphQLField
private Integer id;
private List<String> items;
@GraphQLField
@GraphQLDataFetcher(MyClassDataFetcher.class)
public List<String> items(DataFetchingEnvironment environment, @GraphQLName("take") Integer take, @GraphQLName("after") Integer after)
{
return null;
}
}
@GraphQLField
@GraphQLDataFetcher(ListOfBFetcher.class)
List<B> listOfB(int take){return null};
@GraphQLField
List<B> listOfB(int take, DataFetchingEnvironment environment){
//return the list of B
};