Class GraphQLSchemaGenerator
- java.lang.Object
-
- io.leangen.graphql.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
ResolverBuilderinstances, 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 ofOperationSource. Methods of thewith*OperationSourcefamily 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 instanceOperationMapperwhere actual type mapping is delegated to different instances ofTypeMapper.To customize the mapping process, clients can registers their own
TypeMappers usingwithTypeMappers(TypeMapper...). Runtime conversion between values provided by the GraphQL client and those expected by Java code might be needed. This is handled byInputConverterinstances.Similarly, the conversion between values returned by Java code and those expected by the GraphQL client (if needed) is handled by
OutputConverterinstances. Custom implementations of bothInputConverterandOutputConvertercan be provided usingwithInputConverters(InputConverter[])andwithOutputConverters(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 }}");
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceGraphQLSchemaGenerator.CodeRegistryBuilder
-
Constructor Summary
Constructors Constructor Description GraphQLSchemaGenerator()Default constructorGraphQLSchemaGenerator(String queryRoot, String mutationRoot, String subscriptionRoot)Constructor which allows to customize names of root types.GraphQLSchemaGenerator(String queryRoot, String queryRootDescription, String mutationRoot, String mutationRootDescription, String subscriptionRoot, String subscriptionRootDescription)Constructor which allows to customize names of root types.
-
Method Summary
-
-
-
Constructor Detail
-
GraphQLSchemaGenerator
public GraphQLSchemaGenerator()
Default constructor
-
GraphQLSchemaGenerator
public GraphQLSchemaGenerator(String queryRoot, String mutationRoot, String subscriptionRoot)
Constructor which allows to customize names of root types.- Parameters:
queryRoot- name of query root typemutationRoot- name of mutation root typesubscriptionRoot- name of subscription root type
-
GraphQLSchemaGenerator
public GraphQLSchemaGenerator(String queryRoot, String queryRootDescription, String mutationRoot, String mutationRootDescription, String subscriptionRoot, String subscriptionRootDescription)
Constructor which allows to customize names of root types.- Parameters:
queryRoot- name of query root typemutationRoot- name of mutation root typesubscriptionRoot- name of subscription root type
-
-
Method Detail
-
withOperationsFromSingleton
public GraphQLSchemaGenerator withOperationsFromSingleton(Object serviceSingleton, ResolverBuilder... builders)
RegisterserviceSingletonas a singletonOperationSource, with its class (obtained viaObject.getClass()) as its runtime type, using the providedResolverBuilders to look for methods to be exposed or the globally registeredResolverBuilders if none are provided. All query/mutation methods discovered by analyzing theserviceSingleton's type will be later, in query resolution time, invoked on this specific instance (hence the 'singleton' in the method name). Instances of stateless service classes are commonly registered this way.- Parameters:
serviceSingleton- The singleton bean whose type is to be scanned for query/mutation methods and on which those methods will be invoked in query/mutation execution timebuilders- Custom strategy to use when analyzingbeanType- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withOperationsFromSingleton
public GraphQLSchemaGenerator withOperationsFromSingleton(Object serviceSingleton, Type beanType, ResolverBuilder... builders)
RegisterserviceSingletonas a singletonOperationSource, withbeanTypeas its static type, using the providedResolverBuilders to look for methods to be exposed or the globally registeredResolverBuilders if none are provided. All query/mutation methods discovered by analyzing thebeanTypewill be later, in query resolution time, invoked on this specific instance (hence the 'singleton' in the method name). Instances of stateless service classes are commonly registered this way.- Parameters:
serviceSingleton- The singleton bean whose type is to be scanned for query/mutation methods and on which those methods will be invoked in query/mutation execution timebeanType- Runtime type ofserviceSingleton. Should be explicitly provided when it differs from its class (that can be obtained viaObject.getClass()). This is commonly the case when the class is generic or when the instance has been proxied by a framework. UseTypeTokento get aTypeliteral orTypeFactoryto create it dynamically.builders- Custom strategy to use when analyzingbeanType- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withOperationsFromSingleton
public GraphQLSchemaGenerator withOperationsFromSingleton(Object serviceSingleton, AnnotatedType beanType, ResolverBuilder... builders)
Same aswithOperationsFromSingleton(Object, Type, ResolverBuilder...), except that anAnnotatedTypeis used asserviceSingleton's static type. Needed when type annotations such asGraphQLNonNullnot directly declared on the class should be captured.- Parameters:
serviceSingleton- The singleton bean whose type is to be scanned for query/mutation methods and on which those methods will be invoked in query/mutation execution timebeanType- Runtime type ofserviceSingleton. Should be explicitly provided when it differs from its class (that can be obtained viaObject.getClass()) and when annotations on the type should be kept. UseTypeTokento get anAnnotatedTypeliteral orTypeFactoryto create it dynamically.builders- Custom builders to use when analyzingbeanType- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withOperationsFromSingletons
public GraphQLSchemaGenerator withOperationsFromSingletons(Object... serviceSingletons)
Same aswithOperationsFromSingleton(Object, ResolverBuilder...)except that multiple beans can be registered at the same time.- Parameters:
serviceSingletons- Singleton beans whose type is to be scanned for query/mutation methods and on which those methods will be invoked in query/mutation execution time- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withOperationsFromBean
public GraphQLSchemaGenerator withOperationsFromBean(Supplier<Object> serviceSupplier, Type beanType, ResolverBuilder... builders)
AnalyzesbeanTypeusing the providedResolverBuilders to look for methods to be exposed or the globally registeredResolverBuilders if none are provided, and usesserviceSupplierto obtain an instance on which query/mutation methods are invoked at runtime. Container managed beans (of any scope) are commonly registered this way..- Parameters:
serviceSupplier- The supplier that will be used to obtain an instance on which the exposed methods will be invoked when resolving queries/mutations/subscriptions.beanType- Static type of instances provided byserviceSupplier. UseTypeTokento get aTypeliteral orTypeFactoryto create it dynamically.builders- Custom strategy to use when analyzingbeanType- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withOperationsFromBean
public GraphQLSchemaGenerator withOperationsFromBean(Supplier<Object> serviceSupplier, AnnotatedType beanType, ResolverBuilder... builders)
Same aswithOperationsFromBean(Supplier, Type, ResolverBuilder...), except that anAnnotatedTypeis used as the static type of the instances provided byserviceSupplier. Needed when type annotations such asGraphQLNonNullnot directly declared on the class should be captured.
-
withOperationsFromBean
public GraphQLSchemaGenerator withOperationsFromBean(Supplier<Object> serviceSupplier, Type beanType, Class<?> exposedType, ResolverBuilder... builders)
Same aswithOperationsFromBean(Supplier, Type, ResolverBuilder...), but the actual runtime type of the instances provided byserviceSupplierwill be used to choose the method to invoke at runtime. This is the absolute safest approach to registering beans, and is needed when the instances are proxied by a container (e.g. Spring, CDI or others) and can _not_ be cast tobeanTypeat runtime.- Parameters:
serviceSupplier- The supplier that will be used to obtain an instance on which the exposed methods will be invoked when resolving queries/mutations/subscriptions.beanType- Static type of instances provided byserviceSupplier. UseTypeTokento get aTypeliteral orTypeFactoryto create it dynamically.exposedType- Runtime type of the instances provided byserviceSupplier, not necessarily possible to cast tobeanTypebuilders- Custom strategy to use when analyzingbeanType- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withOperationsFromBean
public GraphQLSchemaGenerator withOperationsFromBean(Supplier<Object> serviceSupplier, AnnotatedType beanType, Class<?> exposedType, ResolverBuilder... builders)
Same aswithOperationsFromBean(Supplier, Type, Class, ResolverBuilder...), except that anAnnotatedTypeis used as the static type of the instances provided byserviceSupplier. Needed when type annotations such asGraphQLNonNullnot directly declared on the class should be captured.
-
withOperationsFromType
public GraphQLSchemaGenerator withOperationsFromType(Type serviceType, ResolverBuilder... builders)
AnalyzesserviceTypeusing the providedResolverBuilders to look for methods to be exposed or the globally registeredResolverBuilders if none are provided. An instance ofserviceTypeon which the exposed methods are invoked at runtime must be explicitly provided as GraphQLrootfor each execution. SeeExecutionInput.Builder.root(Object).- Parameters:
serviceType- Type to analyze for methods to expose. UseTypeTokento get aTypeliteral orTypeFactoryto create it dynamically.builders- Custom strategy to use when analyzingserviceType- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withOperationsFromTypes
public GraphQLSchemaGenerator withOperationsFromTypes(Type... serviceType)
-
withOperationsFromType
public GraphQLSchemaGenerator withOperationsFromType(AnnotatedType serviceType, ResolverBuilder... builders)
Same aswithOperationsFromType(Type, ResolverBuilder...), except that anAnnotatedTypeis used. Needed when type annotations such asGraphQLNonNullnot directly declared on the class should be captured.
-
withOperationsFromTypes
public GraphQLSchemaGenerator withOperationsFromTypes(AnnotatedType... serviceType)
-
withResolverBuilders
public GraphQLSchemaGenerator withResolverBuilders(ResolverBuilder... resolverBuilders)
Globally registersResolverBuilders to be used for sources that don't have explicitly assigned builders.- Parameters:
resolverBuilders- builders to be globally registered- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withResolverBuilders
public GraphQLSchemaGenerator withResolverBuilders(ExtensionProvider<GeneratorConfiguration,ResolverBuilder> provider)
-
withNestedResolverBuilders
public GraphQLSchemaGenerator withNestedResolverBuilders(ResolverBuilder... resolverBuilders)
Globally registersResolverBuilders to be used for sources that don't have explicitly assigned builders.- Parameters:
resolverBuilders- builders to be globally registered- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withNestedResolverBuilders
public GraphQLSchemaGenerator withNestedResolverBuilders(ExtensionProvider<GeneratorConfiguration,ResolverBuilder> provider)
-
withInputFieldBuilders
public GraphQLSchemaGenerator withInputFieldBuilders(InputFieldBuilder... inputFieldBuilders)
-
withInputFieldBuilders
public GraphQLSchemaGenerator withInputFieldBuilders(ExtensionProvider<ExtendedGeneratorConfiguration,InputFieldBuilder> provider)
-
withAbstractInputTypeResolution
public GraphQLSchemaGenerator withAbstractInputTypeResolution()
-
withAbstractInputHandler
public GraphQLSchemaGenerator withAbstractInputHandler(AbstractInputHandler abstractInputHandler)
-
withBasePackages
public GraphQLSchemaGenerator withBasePackages(String... basePackages)
-
withStringInterpolation
public GraphQLSchemaGenerator withStringInterpolation(MessageBundle... messageBundles)
-
withJavaDeprecationRespected
public GraphQLSchemaGenerator withJavaDeprecationRespected(boolean respectJavaDeprecation)
-
withJavaDeprecationReason
public GraphQLSchemaGenerator withJavaDeprecationReason(String deprecationReason)
-
withTypeInfoGenerator
public GraphQLSchemaGenerator withTypeInfoGenerator(TypeInfoGenerator typeInfoGenerator)
-
withValueMapperFactory
public GraphQLSchemaGenerator withValueMapperFactory(ValueMapperFactory valueMapperFactory)
-
withInterfaceMappingStrategy
public GraphQLSchemaGenerator withInterfaceMappingStrategy(InterfaceMappingStrategy interfaceStrategy)
-
withScalarDeserializationStrategy
public GraphQLSchemaGenerator withScalarDeserializationStrategy(ScalarDeserializationStrategy scalarStrategy)
-
withInclusionStrategy
public GraphQLSchemaGenerator withInclusionStrategy(InclusionStrategy inclusionStrategy)
-
withImplementationDiscoveryStrategy
public GraphQLSchemaGenerator withImplementationDiscoveryStrategy(ImplementationDiscoveryStrategy implDiscoveryStrategy)
-
withTypeTransformer
public GraphQLSchemaGenerator withTypeTransformer(TypeTransformer transformer)
-
withTypeMappers
public GraphQLSchemaGenerator withTypeMappers(TypeMapper... typeMappers)
Registers customTypeMappers to be used for mapping Java type to GraphQL types.Ordering of mappers is strictly important as the first
TypeMapperthat supports the given Java type will be used for mapping it.See
TypeMapper.supports(java.lang.reflect.AnnotatedElement, AnnotatedType)- Parameters:
typeMappers- Custom type mappers to register with the builder- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withTypeMappersPrepended
public GraphQLSchemaGenerator withTypeMappersPrepended(TypeMapper... typeMappers)
-
withTypeMappersPrepended
public GraphQLSchemaGenerator withTypeMappersPrepended(ExtensionProvider<GeneratorConfiguration,TypeMapper> provider)
-
withTypeMappers
public GraphQLSchemaGenerator withTypeMappers(ExtensionProvider<GeneratorConfiguration,TypeMapper> provider)
Registers customTypeMappers to be used for mapping Java type to GraphQL types.Ordering of mappers is strictly important as the first
TypeMapperthat supports the given Java type will be used for mapping it.See
TypeMapper.supports(java.lang.reflect.AnnotatedElement, AnnotatedType)- Parameters:
provider- Provides the customized list of TypeMappers to use- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withSchemaTransformers
public GraphQLSchemaGenerator withSchemaTransformers(SchemaTransformer... transformers)
-
withSchemaTransformers
public GraphQLSchemaGenerator withSchemaTransformers(ExtensionProvider<GeneratorConfiguration,SchemaTransformer> provider)
-
withInputConverters
public GraphQLSchemaGenerator withInputConverters(InputConverter<?,?>... inputConverters)
Registers customInputConverters to be used for converting values provided by the GraphQL client into those expected by the corresponding Java method. Only needed in some specific cases when usual deserialization isn't enough, for example, when a client-providedListshould be repackaged into aMap, which is normally done because GraphQL type system has no direct support for maps.Ordering of converters is strictly important as the first
InputConverterthat supports the given Java type will be used for converting it.- Parameters:
inputConverters- Custom input converters to register with the builder- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withInputConvertersPrepended
public GraphQLSchemaGenerator withInputConvertersPrepended(InputConverter<?,?>... inputConverters)
-
withInputConverters
public GraphQLSchemaGenerator withInputConverters(ExtensionProvider<GeneratorConfiguration,InputConverter> provider)
-
withOutputConverters
public GraphQLSchemaGenerator withOutputConverters(OutputConverter<?,?>... outputConverters)
Registers customOutputConverters to be used for converting values returned by the exposed Java method into those expected by the GraphQL client. Only needed in some specific cases when usual serialization isn't enough, for example, when an instance ofMapshould be repackaged into aList, which is normally done because GraphQL type system has no direct support for maps.Ordering of converters is strictly important as the first
OutputConverterthat supports the given Java type will be used for converting it.See
OutputConverter.supports(java.lang.reflect.AnnotatedElement, AnnotatedType)- Parameters:
outputConverters- Custom output converters to register with the builder- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withOutputConvertersPrepended
public GraphQLSchemaGenerator withOutputConvertersPrepended(OutputConverter<?,?>... outputConverters)
-
withOutputConverters
public GraphQLSchemaGenerator withOutputConverters(ExtensionProvider<GeneratorConfiguration,OutputConverter> provider)
-
withTypeAdapters
public GraphQLSchemaGenerator withTypeAdapters(AbstractTypeAdapter<?,?>... typeAdapters)
Type adapters (instances ofAbstractTypeAdapter) are both type mappers and bi-directional converters, implementingTypeMapper,InputConverterandOutputConverter. They're used in the same way as mappers/converters individually, and exist solely because it can sometimes be convenient to group the logic for mapping and converting to/from the same Java type in one place. For example, because GraphQL type system has no notion of maps,Maps require special logic both when mapping them to a GraphQL type and when converting them before and after invoking a Java method. For this reason, all code dealing with translatingMaps is kept in one place inMapToListTypeAdapter.Ordering of mappers/converters is strictly important as the first one supporting the given Java type will be used to map/convert it.
See
withTypeMappers(ExtensionProvider)- Parameters:
typeAdapters- Custom type adapters to register with the builder- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withArgumentInjectors
public GraphQLSchemaGenerator withArgumentInjectors(ArgumentInjector... argumentInjectors)
-
withArgumentInjectors
public GraphQLSchemaGenerator withArgumentInjectors(ExtensionProvider<GeneratorConfiguration,ArgumentInjector> provider)
-
withModules
public GraphQLSchemaGenerator withModules(Module... modules)
-
withModules
public GraphQLSchemaGenerator withModules(ExtensionProvider<GeneratorConfiguration,Module> provider)
-
withResolverInterceptors
public GraphQLSchemaGenerator withResolverInterceptors(ResolverInterceptor... interceptors)
-
withResolverInterceptorFactories
public GraphQLSchemaGenerator withResolverInterceptorFactories(ExtensionProvider<GeneratorConfiguration,ResolverInterceptorFactory> provider)
-
withAdditionalTypes
@Deprecated public GraphQLSchemaGenerator withAdditionalTypes(Collection<graphql.schema.GraphQLType> additionalTypes)
Deprecated.
-
withAdditionalTypes
public GraphQLSchemaGenerator withAdditionalTypes(Collection<? extends graphql.schema.GraphQLType> additionalTypes, Map<String,AnnotatedType> additionalTypeMappings, graphql.schema.GraphQLCodeRegistry codeRegistry)
-
withAdditionalTypes
public GraphQLSchemaGenerator withAdditionalTypes(Collection<? extends graphql.schema.GraphQLType> additionalTypes, Map<String,AnnotatedType> additionalTypeMappings, GraphQLSchemaGenerator.CodeRegistryBuilder codeRegistryUpdater)
-
withAdditionalDirectives
public GraphQLSchemaGenerator withAdditionalDirectives(Type... additionalDirectives)
-
withAdditionalDirectives
public GraphQLSchemaGenerator withAdditionalDirectives(AnnotatedType... additionalDirectives)
-
withAdditionalDirectives
public GraphQLSchemaGenerator withAdditionalDirectives(graphql.schema.GraphQLDirective... additionalDirectives)
-
withTypeComparators
@SafeVarargs public final GraphQLSchemaGenerator withTypeComparators(Comparator<AnnotatedType>... comparators)
-
withTypeComparators
public GraphQLSchemaGenerator withTypeComparators(ExtensionProvider<GeneratorConfiguration,Comparator<AnnotatedType>> provider)
-
withOperationBuilder
public GraphQLSchemaGenerator withOperationBuilder(OperationBuilder operationBuilder)
-
withDirectiveBuilder
public GraphQLSchemaGenerator withDirectiveBuilder(DirectiveBuilder directiveBuilder)
-
withRelayCompliantMutations
public GraphQLSchemaGenerator withRelayCompliantMutations()
Sets a flag that all mutations should be mapped in a Relay-compliant way, using the default name and description for output wrapper fields.- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withRelayCompliantMutations
public GraphQLSchemaGenerator withRelayCompliantMutations(String wrapperFieldName, String wrapperFieldDescription)
Sets a flag signifying that all mutations should be mapped in a Relay-compliant way, using the default name and description for output wrapper fields.- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withRelayNodeInterfaceInference
public GraphQLSchemaGenerator withRelayNodeInterfaceInference(boolean enabled)
Sets the flag controlling whether the Node interface (as defined by the Relay spec) should be automatically inferred for types that have an ID field.- Parameters:
enabled- Whether the inference should be enabled- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withRelayConnectionCheckRelaxed
public GraphQLSchemaGenerator withRelayConnectionCheckRelaxed()
Removes the requirement on queries returning a Connection to comply with the Relay Connection spec- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
withSchemaProcessors
public GraphQLSchemaGenerator withSchemaProcessors(GraphQLSchemaProcessor... processors)
Registers custom schema processors that can perform arbitrary transformations on the schema just before it is built.- Parameters:
processors- Custom processors to call right before the GraphQL schema is built- Returns:
- This
GraphQLSchemaGeneratorinstance, to allow method chaining
-
generate
public graphql.schema.GraphQLSchema generate()
Generates a GraphQL schema based on the results of analysis of the registered sources. All exposed methods will be mapped as queries or mutations and all Java types referred to by those methods will be mapped to corresponding GraphQL types. Such schema can then be used to constructGraphQLinstances. See the example in the description of this class.- Returns:
- A GraphQL schema
-
generateExecutable
public ExecutableSchema generateExecutable()
-
-