span
span

Reputation: 5624

Create a List<A> as GraphQLObjectType

I want to return a list of class A objects from my GraphQLDatafetcher. I know I can return a single A like this:

GraphQLObjectType a = GraphQLAnnotations.object(A.class);
...
GraphQLFieldDefinition.newFieldDefinition().type(a); // omitted boilerplate from query object

Now, I want to return a list of A so I tried something like this:

GraphQLObjectType aList = GraphQLAnnotations.object(List.class);
...
GraphQLFieldDefinition.newFieldDefinition().type(aList); // omitted 

And this:

GraphQLObjectType aList = GraphQLAnnotations.object(new GraphQLList(A.class));
...
GraphQLFieldDefinition.newFieldDefinition().type(aList); // omitted 

Class A is annotated like this:

@GraphQLType
public class A {...}

First attempt returns null and the second attempt does not compile with GraphQLList cannot be applied to java.lang.Class<A>

A workaround is to create a wrapper object that holds the list but it seems like an ugly hack to me. How can I return a list of A using GraphQL java 2.3.0?

Upvotes: 0

Views: 526

Answers (2)

kaqqao
kaqqao

Reputation: 15429

List type isn't a subtype of object type, so you can never make an object type that represents a list. Both of these types are output types, though (list is also an input type). And this should be what you need.

GraphQLObjectType a = GraphQLAnnotations.object(A.class);
GraphQLOutputType listOfA = new GraphQLList(a);

You can then use this type as a field type, as you would a GraphQLObjectType:

GraphQLFieldDefinition.newFieldDefinition().type(listOfA);

Upvotes: 1

Seb James
Seb James

Reputation: 41

I believe you would need to do the following:

GraphQLFieldDefinition.newFieldDefinition().type(new GraphQLList(A));

Upvotes: 0

Related Questions