graphql-java SPQR: how to use @GraphQLUnion annotation?

969 Views Asked by At

I inherited a project using GraphQL in Java with Grapqhl-SPQR spring boot starter package (v 0.0.3). It uses annotations to autogenerate the GraphQL SDL, but I need to improve error handling. From what I have found online, I need to implement a union of different types so the user can query multiple types at the same time. Almost all of the online guides discuss this implementation in SDL. I am trying to figure out how to do this with GraphQL SPQR.

So if I have a type

type User {
  id: ID!
  name: String
}

and another type

type UserError {
  message: String
}

Then I can create a union using union UserResult = User | UserError in SDL so that I can query.

userResult(id: 1) {
  ... on User {
    id
    name
  }
  ... on UserError {
    message
}

How do I create a union in Graphql-SPQR? I know that there is an @GraphQLUnion annotation, but I can't find any working examples of its implementation. Does anyone have examples or can point me to examples?

1

There are 1 best solutions below

0
On
ExplicitUnionInterfaceService unionService = new ExplicitUnionInterfaceService();

GraphQLSchema schema = new TestSchemaGenerator()
        .withOperationsFromSingleton(unionService)
        .generate();
__________________________________________________________________________________        
private static class ExplicitUnionInterfaceService {
    @GraphQLQuery
    public UserInterface userResult(@GraphQLArgument(name = "id") int id) {
        // Not implemented
        return null;
    }
}

@GraphQLUnion(name = "userResult", description = "This union of User and UserError class", possibleTypes = {User.class, UserError.class})
public interface UserInterface {}


public static class User implements UserInterface {public String id; public String name;}
public static class UserError implements UserInterface {public String message;}

You can find the examples here src/test/java/io/leangen/graphql/UnionTest.java