使用americanexpress / nodes与对象进行GraphQL查询

时间:2018-10-29 20:48:23

标签: java graphql

我正在使用GraphQL JVM Client by American Express

这是我要构建的查询:

exercise {
  id
  name
  images(resize: {width: 512, height: 288, background: "ffffff"})
}

这是我创建的DTO:

@GraphQLProperty(name = "exercise")
public class Exercise {

  private Integer id;

  private String name;

  @GraphQLProperty(name = "images", arguments = {@GraphQLArgument(name = "resize")})
  private List<String> images;

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public List<String> getImages() {
    return images;
  }

  public void setImages(List<String> images) {
    this.images = images;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Exercise() {
  }
}

这就是我要如何建立查询:

GraphQLTemplate graphQLTemplate = new GraphQLTemplate();

GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder()
    .url("https://domain/graphql")
    .arguments(
        new Arguments("exercise.images", new Argument("resize", ?))
    )
    .request(Exercise.class)
    .build();

但是我没有得到正确的表达式?

问题是,如何传递结构化参数作为参数?

2 个答案:

答案 0 :(得分:2)

解决方案是使用InputObject类。您的DTO可以保持定义不变,只需添加如下参数:

GraphQLTemplate graphQLTemplate = new GraphQLTemplate();

InputObject resizeInput = new InputObject.Builder()
  .put("width", 512)
  .put("height", 288)
  .put("background", "ffffff")
  .build();

GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder()
    .url("https://domain/graphql")
    .arguments(
        new Arguments("exercise.images", new Argument("resize", resizeInput))
    )
    .request(Exercise.class)
    .build();

您也可以在这篇文章中进一步了解它以及其他一些API的用法(https://americanexpress.io/graphql-for-the-jvm/

希望这会有所帮助!

答案 1 :(得分:0)

好吧,我找到了适合我的解决方案...

我创建了一个“变量”类

public class ResizeVariable {

  private String background;

  public ResizeVariable() {
  }

  public ResizeVariable(String background) {
    this.background = background;
  }

  public String getBackground() {
    return background;
  }

  public void setBackground(String background) {
    this.background = background;
  }

  @Override
  public String toString() {
    return "{background: \""+background+"\"}";
  }

}

,缺少的是重写toString()方法。然后,这是可能的:

GraphQLTemplate graphQLTemplate = new GraphQLTemplate();

GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder()
  .url("https://domain/graphql")
  .arguments(
    new Arguments("exercise.images",
      new Argument("resize", new ResizeVariable("ffffff")))
  )
  .request(Exercise.class)
  .build();

这将导致正确的查询。