Class GraphQLSchemaGenerator


  • public class GraphQLSchemaGenerator
    extends Object

    This class is the main entry point to the library. It is used to generate a GraphQL schema by analyzing the registered classes and exposing the chosen methods as GraphQL queries or mutations. The process of choosing the methods to expose is delegated to ResolverBuilder instances, and a different set of builders can be attached to each registered class. One such coupling of a registered class and a set of builders is modeled by an instance of OperationSource. Methods of the with*OperationSource family are used to register sources to be analyzed.

    Builders can also be registered globally (to be used when none are provided explicitly) via withResolverBuilders(ResolverBuilder...). The process of mapping the Java methods to GraphQL queries/mutations will also transparently map all encountered Java types to corresponding GraphQL types. The entire mapping process is handled by an instance OperationMapper where actual type mapping is delegated to different instances of TypeMapper.

    To customize the mapping process, clients can registers their own TypeMappers using withTypeMappers(TypeMapper...). Runtime conversion between values provided by the GraphQL client and those expected by Java code might be needed. This is handled by InputConverter instances.

    Similarly, the conversion between values returned by Java code and those expected by the GraphQL client (if needed) is handled by OutputConverter instances. Custom implementations of both InputConverter and OutputConverter can be provided using withInputConverters(InputConverter[]) and withOutputConverters(OutputConverter[]) respectively.

    Example:

     
     UserService userService = new UserService(); //could also be injected by a framework
     GraphQLSchema schema = new GraphQLSchemaGenerator()
          .withOperationsFromSingletons(userService) //register an operations source and use the default strategy
          .withNestedResolverBuildersForType(User.class, new BeanResolverBuilder()) //customize how queries are extracted from User.class
          .generate();
     GraphQL graphQL = new GraphQL(schema);
    
     //keep the reference to GraphQL instance and execute queries against it.
     //this query selects a user by ID and requests name and regDate fields only
     ExecutionResult result = graphQL.execute(
     "{ user (id: 123) {
          name,
          regDate
      }}");