Search code examples
javaapigraphqlgraphql-java

Is there a way to group GraphQL query fields into sub/nested query groups?


I am using GraphQL-Java and I am new to GraphQL.

I am trying to find a way to organize my API in the same way it's done in the GraphQL Hub

Essentially, I want to have my RootQuery as the entry point (like the GraphQLHubAPI in the GraphQL Hub) and then sub groups like Reddit, Github etc in the GraphQL Hub)

Inside the RootQuery

Inside RedditAPI

I am confused as to what the RedditAPI should be and how I should do the wiring for it. If this is an Object Type, it requires a DataFetcher or some way to resolve request. In their schemas they expose it as QueryObjectType (using JS)

How can I replicate the same structure using GraphQL-Java?


Solution

  • So apparently the answer is to use a data fetcher that returns a dummy object for the "sub-group" objects. This creates the "path" to your leafs. And you can the handle the leafs in the wiring

    For example for the Reddit scenario you can a schema like this

    schema {
        query: RootQuery
    }
    
    type RootQuery {
        RedditAPI: RedditAPI
    }
    
    type RedditAPI {
        users: [Users]
        subreddits(name: String!): [subreddit]
    }
    

    And then wire it up like this

    RuntimeWiring.newRuntimeWiring()
                    .type(newTypeWiring("RootQuery")
                            .dataFetcher("RedditAPI", new DataFetcher() {
                                @Override
                                public Object get(DataFetchingEnvironment dataFetchingEnvironment) {
                                    return RedditAPI.newBuilder().build();
                                }
                            })
                    )
                    .type(newTypeWiring("RedditAPI")
                            .dataFetcher("users", usersDataFetcher)
                            .dataFetcher("subreddits", subredditsDataFetcher)
                    )
                    .build();