spring Graphql Sping Boot 客户端

mtb9vblg  于 2022-12-02  发布在  Spring
关注(0)|答案(1)|浏览(160)

伙计们,我有个问题:我在spring graphql上有微服务,它工作正常,请求的例子在这里:
enter image description here
但是如果我需要传递对象列表的话,我不清楚如何编写客户端。我试着使用GraphqlTemplate(implementation '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,但不清楚如何传递数组

hmmo2u0o

hmmo2u0o1#

假设您为Person定义了一个模式,如下所示:

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

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

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

相关问题