在java中发送GraphQl查询

Hem*_*dar 13 java graphql graphql-java

我是GraphQL的新手.我知道这是非常基本的问题.但是尝试花费大量时间而我无法做到.

我的要求是我需要使用java类中的graphql-java api方法发送GraphQL查询.

这是查询:

{
  contentItem(itemId: 74152479) {
    slug
    updatedAt
    contributors {
      id
      isFreeForm
      name
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ch3*_*hau 7

首先,您必须更详细地说明您的问题,从您的示例查询中我实际上无法看到您遇到问题的哪个部分,它可能在参数,嵌套对象数据获取器中

我也是GraphQL(java)的新手,而不是与你分享直接答案,我打算告诉你我是如何解决类似问题的.

graphql-java在他们的测试用例中确实做得很好.您可以在这里参考:https://github.com/andimarek/graphql-java/tree/master/src/test/groovy/graphql以获得有关如何创建和查询GraphQL架构的一些想法.

参数

我在这里发现了类似你的类似案例:https: //github.com/andimarek/graphql-java/blob/master/src/test/groovy/graphql/StarWarsSchema.java#L131

newFieldDefinition()
    .name("human")
    .type(humanType)
    .argument(newArgument()
        .name("id")
        .description("id of the human")
        .type(new GraphQLNonNull(GraphQLString))
        .build())
    .dataFetcher(StarWarsData.getHumanDataFetcher())
    .build())
Run Code Online (Sandbox Code Playgroud)

在这种情况下,只定义了一个参数,即id.new GraphQLNonNull(GraphQLString)告诉我们这是一个必需的字符串参数.

字段

对于字段,它定义在humanType,您可以参考https://github.com/andimarek/graphql-java/blob/master/src/test/groovy/graphql/StarWarsSchema.java#L51.嵌套字段只是具有一些字段的另一种类型,例如,.type(nestedHumanType)

数据提取器

毕竟,您可能会处理参数id并返回一些数据.你可以参考这里的例子:https://github.com/andimarek/graphql-java/blob/master/src/test/groovy/graphql/StarWarsData.groovy#L84

为了使我的代码看起来更干净,通常我会为DataFetcher创建一个单独的类,例如:

public class HumanDataFetcher implements DataFetcher {
    @Override
    public Object get(DataFetchingEnvironment environment) {
        String id = (String)environment.get("id");
        // Your code here
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • 答案中提供的链接不再有效。 (2认同)