Mapping and accessing "partial" responses
See original GitHub issueI’m having trouble wrapping my head around the mapping between whatever GraphQLResult returns after a successful query and the generated classes.
I’m executing a mutation and fetch only a single field “access_token” from the response by setting the appropriate projection. The autogenerated response object “LoginUserResponse” has another field “user”, which I’m not interested in.
public void login() throws IOException, GraphQLException {
LoginUserInput input = new LoginUserInput();
input.setUsername(this.username);
input.setPassword(this.password);
LoginUserMutationRequest query = new LoginUserMutationRequest();
query.setUser_data(input);
// Only fetch field access_token, ignore all other fields
LoginUserResponseResponseProjection projection = new LoginUserResponseResponseProjection().access_token();
GraphQLResult<Map<String, LoginUserResponse>> result = this.queryEntity(query, projection);
System.out.println(result.getData().get(query.getOperationName()).getAccess_token());
}
public <Q extends GraphQLOperationRequest, P extends GraphQLResponseProjection, R> GraphQLResult<Map<String, R>> queryEntity(Q query, P projection) throws GraphQLException {
GraphQLRequest request = new GraphQLRequest(query, projection);
GraphQLResult<Map<String, R>> result = restTemplate.exchange(URI.create(this.endpoint + "/***/api/graphql"),
HttpMethod.POST,
new HttpEntity<String>(request.toHttpJsonBody(), createHeaders(request)),
new ParameterizedTypeReference<GraphQLResult<Map<String, R>>>() {})
.getBody();
if (result.hasErrors()) {
throw new GraphQLException(result.getErrors());
}
return result;
}
This leads to this error:
java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class com.***.***.model.LoginUserResponse (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; com.***.***.model.LoginUserResponse is in unnamed module of loader 'app')
Which makes sense, as the class LoginResponse would expect the field ‘user’ to be not null, but I’m not fetching this field, so constructing an instance of LoginResponse is impossible.
Could anyone give me a hint on how to properly access the fields I fetched? I can see that there are Mapper definitions in the examples, but I’m a little confused regarding the differences between ProductTO and Product, as I can not find two different classes for an entity in my autogenerated code.
Any help very much appreciated!
Issue Analytics
- State:
- Created 3 years ago
- Comments:11 (5 by maintainers)
Looks good to me. Having the operation name being resolved automatically is a nice plus! Will this work with Lists?
@philipp-schmidt I’ve already started working on this. Here’s the additional class that will be generated:
So that in the client code it will look a bit simplified:
Please let me know what you think