【问题标题】:Graphql spring boot clientGraphql spring boot 客户端
【发布时间】:2022-11-28 05:54:21
【问题描述】:

伙计们,我有一个问题:我在 spring graphql 上有微服务,它工作正常,请求示例在这里:

enter image description here

但是,如果我需要传达对象列表,则不清楚如何为这种情况编写客户端。我尝试使用 GraphqlTemplate(实现'com.github.americanexpress:nodes:0.5.0')但我没有找到任何将列表传递给请求的示例。使用其他库可能更糟。

有人用过类似的东西吗?

@Service
public class PersonService {

    private final GraphQLTemplate graphQLTemplate = new GraphQLTemplate();
    private final String url = "http://localhost:8084/graphql";
    
    
    public List<Person> getPersonsByIds() {
  
        GraphQLRequestEntity requestEntity;
        try {
            requestEntity = GraphQLRequestEntity.Builder()
                .url(url)
                .requestMethod(GraphQLTemplate.GraphQLMethod.QUERY)
                .request("query($personIds: [BigInteger]) {\n" +
                    "  getPersonsByIds(personIds : $personIds ) {\n" +
                    "    firstName\n" +
                    "    middleName\n" +
                    "    lastName\n" +
                    "    birthDt\n" +
                    "  }\n" +
                    "}"
                )
                .variables(new Variable<>("personId", "2477142261427744786")) // just enable to pass only one id and got 1 person
                .build();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        return graphQLTemplate.query(requestEntity, ResponseGetPersonsByIds.class).getResponse().getGetPersonsByIds();
    }    
}    

我了解如何仅传递 1 个 id 但不清楚如何传递数组

【问题讨论】:

    标签: java spring spring-boot graphql client


    【解决方案1】:

    假设您像这样为 Person 定义了一个模式:

    type Person{
        firstName: String
        // other fields...
    }
    

    然后您可以使用 @SchemaMapping 返回该对象的列表:

    @SchemaMapping(typeName = "Query",value = "personList")
    public List<Person> getPersonsByIds() {
      return personService.getPersonsByIds();
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-31
      • 2018-09-04
      • 2015-08-26
      • 2019-06-29
      • 2016-09-28
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多