spring-graphql
spring-graphql copied to clipboard
How to decode Union!
spring for graphql works great. I came across this issue & not sure how to decode this with HttpGraphqlClient retrieve or execute method.
union Notification = TweetSuggestion | SomeoneLikedYourTweet | SomeoneFollowsYou
@kitcars I don't think this issue has been triaged yet. If you've found a solution could you share that with us please?
One option is to use Jackson's polymorphic types feature and create a marker interface to hold the @JsonTypeInfo.
For example, given:
type Query {
search: [SearchResult!]
}
union SearchResult = Book | Author
type Book {
title: String!
}
type Author {
name: String!
}
You could declare:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "__typename",
visible = true
)
@JsonSubTypes({
@JsonSubTypes.Type(value = Book.class, name = "Book"),
@JsonSubTypes.Type(value = Author.class, name = "Author")
})
public interface SearchResult {
}
public class Book implements SearchResult {
// constructor, getter/setters...
}
public class Author implements SearchResult {
// constructor, getter/setters...
}
Then for your client:
HttpGraphQlClient client = HttpGraphQlClient.builder()
.webClient(builder -> builder.baseUrl("http://localhost:8080/graphql"))
.build();
String document = "query {\n" +
" search {\n" +
" __typename\n" +
" ...on Book {\n" +
" title\n" +
" }\n" +
" ...on Author {\n" +
" name\n" +
" }\n" +
" }\n" +
"}";
List<SearchResult> results = client.document(document)
.retrieve("search")
.toEntityList(SearchResult.class)
.block();
I'm closing this for now, as it seems possible, but if necessary we'll reopen.