spring-graphql icon indicating copy to clipboard operation
spring-graphql copied to clipboard

How to decode Union!

Open kitkars opened this issue 3 years ago • 1 comments

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

kitkars avatar Aug 07 '22 21:08 kitkars

@kitcars I don't think this issue has been triaged yet. If you've found a solution could you share that with us please?

bclozel avatar Aug 13 '22 15:08 bclozel

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();

rstoyanchev avatar Nov 03 '22 12:11 rstoyanchev

I'm closing this for now, as it seems possible, but if necessary we'll reopen.

rstoyanchev avatar Nov 03 '22 12:11 rstoyanchev