Java Code Examples for graphql.schema.GraphQLSchema#Builder

The following examples show how to use graphql.schema.GraphQLSchema#Builder . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private GraphQLSchema generateGraphQLSchema() {
    GraphQLSchema.Builder schemaBuilder = GraphQLSchema.newSchema();

    createGraphQLEnumTypes();
    createGraphQLInterfaceTypes();
    createGraphQLObjectTypes();
    createGraphQLInputObjectTypes();

    addQueries(schemaBuilder);
    addMutations(schemaBuilder);

    schemaBuilder.additionalTypes(new HashSet<>(enumMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(interfaceMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(typeMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(inputMap.values()));

    codeRegistryBuilder.fieldVisibility(getGraphqlFieldVisibility());
    schemaBuilder = schemaBuilder.codeRegistry(codeRegistryBuilder.build());

    // register error info
    ErrorInfoMap.register(schema.getErrors());

    return schemaBuilder.build();
}
 
Example 2
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private void addQueries(GraphQLSchema.Builder schemaBuilder) {

        GraphQLObjectType.Builder queryBuilder = GraphQLObjectType.newObject()
                .name(QUERY)
                .description("Query root");

        if (schema.hasQueries()) {
            Set<Operation> queries = schema.getQueries();
            for (Operation queryOperation : queries) {
                GraphQLFieldDefinition graphQLFieldDefinition = createGraphQLFieldDefinitionFromOperation(QUERY,
                        queryOperation);
                queryBuilder = queryBuilder.field(graphQLFieldDefinition);
            }
        }

        GraphQLObjectType query = queryBuilder.build();
        schemaBuilder.query(query);
    }
 
Example 3
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private void addMutations(GraphQLSchema.Builder schemaBuilder) {

        if (schema.hasMutations()) {
            GraphQLObjectType.Builder mutationBuilder = GraphQLObjectType.newObject()
                    .name(MUTATION)
                    .description("Mutation root");

            Set<Operation> mutations = schema.getMutations();
            for (Operation mutationOperation : mutations) {
                GraphQLFieldDefinition graphQLFieldDefinition = createGraphQLFieldDefinitionFromOperation(MUTATION,
                        mutationOperation);
                mutationBuilder = mutationBuilder.field(graphQLFieldDefinition);
            }

            GraphQLObjectType mutation = mutationBuilder.build();
            if (mutation.getFieldDefinitions() != null && !mutation.getFieldDefinitions().isEmpty()) {
                schemaBuilder.mutation(mutation);
            }
        }
    }
 
Example 4
Source File: SchemaTransformer.java    From federation-jvm with MIT License 4 votes vote down vote up
@NotNull
public final GraphQLSchema build() throws SchemaProblem {
    final List<GraphQLError> errors = new ArrayList<>();

    // Make new Schema
    final GraphQLSchema.Builder newSchema = GraphQLSchema.newSchema(originalSchema);

    final GraphQLObjectType originalQueryType = originalSchema.getQueryType();

    final GraphQLCodeRegistry.Builder newCodeRegistry =
            GraphQLCodeRegistry.newCodeRegistry(originalSchema.getCodeRegistry());

    // Print the original schema as sdl and expose it as query { _service { sdl } }
    final String sdl = sdl(originalSchema);
    final GraphQLObjectType.Builder newQueryType = GraphQLObjectType.newObject(originalQueryType)
            .field(_Service.field);
    newCodeRegistry.dataFetcher(FieldCoordinates.coordinates(
            originalQueryType.getName(),
            _Service.fieldName
            ),
            (DataFetcher<Object>) environment -> DUMMY);
    newCodeRegistry.dataFetcher(FieldCoordinates.coordinates(
            _Service.typeName,
            _Service.sdlFieldName
            ),
            (DataFetcher<String>) environment -> sdl);

    // Collecting all entity types: Types with @key directive and all types that implement them
    final Set<String> entityTypeNames = originalSchema.getAllTypesAsList().stream()
            .filter(t -> t instanceof GraphQLDirectiveContainer &&
                    ((GraphQLDirectiveContainer) t).getDirective(FederationDirectives.keyName) != null)
            .map(GraphQLNamedType::getName)
            .collect(Collectors.toSet());

    final Set<String> entityConcreteTypeNames = originalSchema.getAllTypesAsList()
            .stream()
            .filter(type -> type instanceof GraphQLObjectType)
            .filter(type -> entityTypeNames.contains(type.getName()) ||
                    ((GraphQLObjectType) type).getInterfaces()
                            .stream()
                            .anyMatch(itf -> entityTypeNames.contains(itf.getName())))
            .map(GraphQLNamedType::getName)
            .collect(Collectors.toSet());

    // If there are entity types install: Query._entities(representations: [_Any!]!): [_Entity]!
    if (!entityConcreteTypeNames.isEmpty()) {
        newQueryType.field(_Entity.field(entityConcreteTypeNames));

        final GraphQLType originalAnyType = originalSchema.getType(_Any.typeName);
        if (originalAnyType == null) {
            newSchema.additionalType(_Any.type(coercingForAny));
        }

        if (entityTypeResolver != null) {
            newCodeRegistry.typeResolver(_Entity.typeName, entityTypeResolver);
        } else {
            if (!newCodeRegistry.hasTypeResolver(_Entity.typeName)) {
                errors.add(new FederationError("Missing a type resolver for _Entity"));
            }
        }

        final FieldCoordinates _entities = FieldCoordinates.coordinates(originalQueryType.getName(), _Entity.fieldName);
        if (entitiesDataFetcher != null) {
            newCodeRegistry.dataFetcher(_entities, entitiesDataFetcher);
        } else if (entitiesDataFetcherFactory != null) {
            newCodeRegistry.dataFetcher(_entities, entitiesDataFetcherFactory);
        } else if (!newCodeRegistry.hasDataFetcher(_entities)) {
            errors.add(new FederationError("Missing a data fetcher for _entities"));
        }
    }

    if (!errors.isEmpty()) {
        throw new SchemaProblem(errors);
    }

    return newSchema
            .query(newQueryType.build())
            .codeRegistry(newCodeRegistry.build())
            .build();
}
 
Example 5
Source File: GraphQLSchemaGenerator.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
/**
 * 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 construct {@link graphql.GraphQL} instances. See the example in the description of this class.
 *
 * @return A GraphQL schema
 */
public GraphQLSchema generate() {
    init();

    final String queryRootName = messageBundle.interpolate(queryRoot);
    final String mutationRootName = messageBundle.interpolate(mutationRoot);
    final String subscriptionRootName = messageBundle.interpolate(subscriptionRoot);

    BuildContext buildContext = new BuildContext(
            basePackages, environment, new OperationRegistry(operationSourceRegistry, operationBuilder, inclusionStrategy,
            typeTransformer, basePackages, environment), new TypeMapperRegistry(typeMappers),
            new SchemaTransformerRegistry(transformers), valueMapperFactory, typeInfoGenerator, messageBundle, interfaceStrategy,
            scalarStrategy, typeTransformer, abstractInputHandler, new InputFieldBuilderRegistry(inputFieldBuilders),
            interceptorFactory, directiveBuilder, inclusionStrategy, relayMappingConfig, additionalTypes.values(),
            additionalDirectiveTypes, typeComparator, implDiscoveryStrategy, codeRegistry);
    OperationMapper operationMapper = new OperationMapper(queryRootName, mutationRootName, subscriptionRootName, buildContext);

    GraphQLSchema.Builder builder = GraphQLSchema.newSchema();
    builder.query(newObject()
            .name(queryRootName)
            .description(messageBundle.interpolate(queryRootDescription))
            .fields(operationMapper.getQueries())
            .build());

    List<GraphQLFieldDefinition> mutations = operationMapper.getMutations();
    if (!mutations.isEmpty()) {
        builder.mutation(newObject()
                .name(mutationRootName)
                .description(messageBundle.interpolate(mutationRootDescription))
                .fields(mutations)
                .build());
    }

    List<GraphQLFieldDefinition> subscriptions = operationMapper.getSubscriptions();
    if (!subscriptions.isEmpty()) {
        builder.subscription(newObject()
                .name(subscriptionRootName)
                .description(messageBundle.interpolate(subscriptionRootDescription))
                .fields(subscriptions)
                .build());
    }

    Set<GraphQLType> additional = new HashSet<>(additionalTypes.values());
    additional.addAll(buildContext.typeRegistry.getDiscoveredTypes());
    builder.additionalTypes(additional);

    builder.additionalDirectives(new HashSet<>(additionalDirectives.values()));
    builder.additionalDirectives(new HashSet<>(operationMapper.getDirectives()));

    builder.codeRegistry(buildContext.codeRegistry.build());

    applyProcessors(builder, buildContext);
    buildContext.executePostBuildHooks();
    return builder.build();
}
 
Example 6
Source File: GraphQLSchemaGenerator.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
private void applyProcessors(GraphQLSchema.Builder builder, BuildContext buildContext) {
    for (GraphQLSchemaProcessor processor : processors) {
        processor.process(builder, buildContext);
    }
}
 
Example 7
Source File: GraphQLAutoConfiguration.java    From spring-boot-starter-graphql with Apache License 2.0 3 votes vote down vote up
@Bean
public GraphQL graphql () {
  // build the Query (Read) portion of the GraphQL schema
  Builder queryBuilder = GraphQLObjectType.newObject().name("Query");
  
  queryBuilders.forEach(qb->qb.build(queryBuilder));
  
  // build the Mutation (Write) portion of the GraphQL schema    
  
  Builder mutationBuilder = GraphQLObjectType.newObject().name("Mutation");
  
  mutationBuilders.forEach(mb->mb.build(mutationBuilder));
  
  Builder subscriptionBuilder = GraphQLObjectType.newObject().name("Subscription");
  
  subscriptionBuilders.forEach(sb->sb.build(subscriptionBuilder));
  
  // build all types
  
  List<GraphQLType> types = typeBuilders.stream().map(tb->tb.build()).collect(Collectors.toList());
  
  // build the GraphQL schema
  
  GraphQLSchema.Builder schemaBuilder = GraphQLSchema.newSchema();
  
  if(queryBuilders.size() > 0) {
    schemaBuilder.query(queryBuilder);
  }
  
  if(mutationBuilders.size() > 0) {
    schemaBuilder.mutation(mutationBuilder);
  }
  
  if(subscriptionBuilders.size() > 0) {
    schemaBuilder.subscription(subscriptionBuilder);
  }
  
  return GraphQL.newGraphQL(schemaBuilder.additionalTypes(new HashSet<>(types)).build()).build();
}
 
Example 8
Source File: GraphQLExecutor.java    From graphql-jpa with MIT License 2 votes vote down vote up
/**
 * Gets the builder that was used to create the Schema that this executor is basing its query executions on. The
 * builder can be used to update the executor with the {@link #updateSchema(GraphQLSchema.Builder)} method.
 * @return An instance of a builder.
 */
public GraphQLSchema.Builder getBuilder() {
    return builder;
}
 
Example 9
Source File: GraphQLExecutor.java    From graphql-jpa with MIT License 2 votes vote down vote up
/**
 * Uses the given builder to re-create and replace the {@link GraphQLSchema}
 * that this executor uses to execute its queries.
 *
 * @param builder The builder to recreate the current {@link GraphQLSchema} and {@link GraphQL} instances.
 * @return The same executor but with a new {@link GraphQL} schema.
 */
public GraphQLExecutor updateSchema(GraphQLSchema.Builder builder) {
    this.builder = builder;
    createGraphQL(null);
    return this;
}
 
Example 10
Source File: GraphQLExecutor.java    From graphql-jpa with MIT License 2 votes vote down vote up
/**
 * Uses the given builder to re-create and replace the {@link GraphQLSchema}
 * that this executor uses to execute its queries.
 *
 * @param builder The builder to recreate the current {@link GraphQLSchema} and {@link GraphQL} instances.
 * @param attributeMappers Custom {@link AttributeMapper} list, if you need any non-standard mappings.
 * @return The same executor but with a new {@link GraphQL} schema.
 */
public GraphQLExecutor updateSchema(GraphQLSchema.Builder builder, Collection<AttributeMapper> attributeMappers) {
    this.builder = builder;
    createGraphQL(attributeMappers);
    return this;
}
 
Example 11
Source File: GraphQLSchemaProcessor.java    From graphql-spqr with Apache License 2.0 votes vote down vote up
GraphQLSchema.Builder process(GraphQLSchema.Builder schemaBuilder, BuildContext buildContext);