gpt4 book ai didi

java - 如何从 java spring-boot 应用程序调用 GraphQL api?是否有支持 graphQL 查询形成的注释?

转载 作者:行者123 更新时间:2023-12-05 02:35:34 49 4
gpt4 key购买 nike

我正在寻找一种解决方案来实现来自 spring-boot 应用程序的 GraphQL api 调用,查询模式如下:

查询{

getDetailsByRefNumber(RefNumbers: "")

{

field1,

field2,

field3

}

有人知道如何实现吗?通过以下链接之一,但没有找到任何解决方案

Are there any Java based Graphql client to invoke graphql server from java code?

最佳答案

您可以使用位于以下位置的“graphql-webclient-spring-boot-starter”库:

https://github.com/graphql-java-kickstart/graphql-spring-webclient

<!-- https://mvnrepository.com/artifact/com.graphql-java-kickstart/graphql-webclient-spring-boot-starter -->
<dependency>
<groupId>com.graphql-java-kickstart</groupId>
<artifactId>graphql-webclient-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>

示例实现可以是这样的:

假设您有 MyEntity 对象:

public class MyEntity
{
String field1;
String field2;
String field3;
//getter and setters here
}

“src/main/resources”文件夹下还有两个 graphql 查询文件:

query1.graphql:

#query1.graphql
#this query returns a list of some_detail_entity
query getDetailListByRefNumber($RefNumber: String!){
some_detail_entity(where: {RefNumber : { _eq: $RefNumber } }) {
field1
field2
field3
}
}

query2.graphql:

#query2.graphql
#this query returns a single some_detail_entity
query getDetailByRefNumber($RefNumber: String!){
some_detail_entity_by_pk(RefNumber : $RefNumber) {
field1
field2
field3
}
}

您可以使用此代码段调用 graphql 服务器来查询和获取一些数据:

ObjectMapper objectMapper = new ObjectMapper();

WebClient webClient = WebClient.builder()
.baseUrl("https://endpoint-url-of-graphql.com")//url of graphql instance
.defaultHeader("auth-token", "some-cryptic-code-if-required")//if auth header not required, just delete this line
.build();

GraphQLWebClient graphqlClient = GraphQLWebClient.newInstance(webClient, objectMapper);

//if expecting a single entity (not array)
MyObject entity = graphqlClient.post("query2.graphql",
Map.of("RefNumber", "A7EED900-9BB4-486F-9F7C-2136E61E2278"), MyEntity.class)
.block();


//if expecting a list of entity (array)
var response = graphqlClient.post(GraphQLRequest.builder().resource("query1.graphql")
.variables(Map.of("RefNumber", "A7EED900-9BB4-486F-9F7C-2136E61E2278")).build())
.block();

List<MyEntity> entityList = response.getFirstList(MyEntity.class);

关于java - 如何从 java spring-boot 应用程序调用 GraphQL api?是否有支持 graphQL 查询形成的注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70519410/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com