I have a spring boot GraphQL API and I want to consume it in another spring boot app using GraphQL Client. I am using spring boot version 3.
when I execute mutate which works as data is added to the database, I am not able to figure out how to convert the received response to java class. below is my ClientService class.
any advise?
note: it only worked for me is by using Map to get key value pairs of the received object.
ObjectMapper didnt work.
package com.webtech.graphqlclient.service;
import com.webtech.graphqlclient.webmodels.CreateStudentRequest;
import com.webtech.graphqlclient.webmodels.StudentResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.graphql.client.HttpGraphQlClient;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Service
public class ClientService {
private final HttpGraphQlClient graphQlClient;
public ClientService(@Value("${graphql.api.url}")String apiUrl) {
WebClient client = WebClient.builder()
.baseUrl(apiUrl)
.build();
graphQlClient = HttpGraphQlClient.builder(client).build();
}
public StudentResponse getStudent(int id){
Map<String, Object> variables = new HashMap<>();
variables.put("id", id);
String query = """
query getStudent($id: Int) {
getStudent(id: $id) {
id
firstName
lastName
email
street
city
fullName
subjects(subjectNameFilter: All) {
id
subjectName
marksObtained
}
}
}
""";
return graphQlClient.document(query)
.variables(variables)
.retrieve("getStudent")
.toEntity(StudentResponse.class)
.block();
}
public StudentResponse createStudent(CreateStudentRequest createStudentRequest) {
Map<String, Object> variables = new HashMap<>();
variables.put("createStudentRequest", createStudentRequest);
String mutationQuery = """
mutation createStudent($createStudentRequest: CreateStudentRequest) {
createStudent(createStudentRequest: $createStudentRequest) {
id
firstName
lastName
email
street
city
fullName
subjects(subjectNameFilter: All) {
id
subjectName
marksObtained
}
}
}
""";
Map<String, Object> data =
Objects.requireNonNull(graphQlClient.document(mutationQuery)
.variables(variables)
.execute()
.block())
.getData();
Map<String, Object> entity = (Map<String, Object>) data.get("createStudent");
int id = (int) entity.get("id");
return getStudent(id);
}
}