Java Code Examples for graphql.schema.GraphQLObjectType#Builder

The following examples show how to use graphql.schema.GraphQLObjectType#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 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 2
Source File: RTEFieldFactory.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    // Add the copy field as string without filters
    parentGraphQLType.field(GraphQLFieldDefinition.newFieldDefinition()
        .name(getGraphQLName(graphQLFieldName) + FIELD_SUFFIX_RAW)
        .description(XmlUtils.selectSingleNodeValue(contentTypeField, titleXPath))
        .type(GraphQLString));

    // Add the original as string with text filters
    graphQLField.type(GraphQLString);
    graphQLField.argument(TEXT_FILTER);
}
 
Example 3
Source File: InputFieldFactory.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    if (Boolean.parseBoolean(XmlUtils.selectSingleNodeValue(contentTypeField, tokenizeXPath))) {
        // Add the tokenized field as string with text filters
        parentGraphQLType.field(GraphQLFieldDefinition.newFieldDefinition()
            .name(StringUtils.substringBeforeLast(graphQLFieldName, FIELD_SEPARATOR) + FIELD_SUFFIX_TOKENIZED)
            .description("Tokenized version of " + contentTypeFieldId)
            .type(GraphQLString)
            .argument(TEXT_FILTER));
    }

    // Add the original according to the postfix
    setTypeFromFieldName(contentTypeFieldId, graphQLField);
}
 
Example 4
Source File: FullTypeGenerator.java    From graphql-java-type-generator with MIT License 6 votes vote down vote up
protected GraphQLOutputType generateOutputType(Object object) {
    //An enum is a special case in both java and graphql,
    //and must be checked for while generating other kinds of types
    GraphQLEnumType enumType = generateEnumType(object);
    if (enumType != null) {
        return enumType;
    }
    
    List<GraphQLFieldDefinition> fields = getOutputFieldDefinitions(object);
    if (fields == null || fields.isEmpty()) {
        return null;
    }
    
    String typeName = getGraphQLTypeNameOrIdentityCode(object);
    GraphQLObjectType.Builder builder = newObject()
            .name(typeName)
            .fields(fields)
            .description(getTypeDescription(object));
    
    GraphQLInterfaceType[] interfaces = getInterfaces(object);
    if (interfaces != null) {
        builder.withInterfaces(interfaces);
    }
    return builder.build();
}
 
Example 5
Source File: EnumMapToObjectTypeAdapter.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQLObjectType toGraphQLType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLObjectType.Builder builder = GraphQLObjectType.newObject()
            .name(typeName)
            .description(buildContext.typeInfoGenerator.generateTypeDescription(javaType, buildContext.messageBundle));

    Enum<E>[] keys = ClassUtils.<E>getRawType(getElementType(javaType, 0).getType()).getEnumConstants();
    Arrays.stream(keys).forEach(enumValue -> {
        String fieldName = enumMapper.getValueName(enumValue, buildContext.messageBundle);
        TypedElement element = new TypedElement(getElementType(javaType, 1), ClassUtils.getEnumConstantField(enumValue));
        buildContext.codeRegistry.dataFetcher(FieldCoordinates.coordinates(typeName, fieldName), (DataFetcher) e -> ((Map)e.getSource()).get(enumValue));
        builder.field(GraphQLFieldDefinition.newFieldDefinition()
                .name(fieldName)
                .description(enumMapper.getValueDescription(enumValue, buildContext.messageBundle))
                .deprecate(enumMapper.getValueDeprecationReason(enumValue, buildContext.messageBundle))
                .type(env.forElement(element).toGraphQLType(element.getJavaType()))
                .build());
    });
    return builder.build();
}
 
Example 6
Source File: RepeatGroupFieldFactory.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    // For Repeating Groups we need to create a wrapper type and do everything all over
    GraphQLObjectType.Builder repeatType = GraphQLObjectType.newObject()
        .name(parentGraphQLTypeName + FIELD_SEPARATOR + graphQLFieldName + FIELD_SUFFIX_ITEM)
        .description("Item for repeat group of " + contentTypeFieldId);

    List<Node> fields =
        XmlUtils.selectNodes(contentTypeField, fieldsXPath, Collections.emptyMap());

    // Call recursively for all fields in the repeating group
    if (CollectionUtils.isNotEmpty(fields)) {
        fields.forEach(f -> typeFactory.createField(contentTypeDefinition, f, parentGraphQLTypeName, repeatType));
    }

    GraphQLObjectType wrapperType = GraphQLObjectType.newObject()
        .name(parentGraphQLTypeName + FIELD_SEPARATOR + graphQLFieldName + FIELD_SUFFIX_ITEMS)
        .description("Wrapper for list of items of " + contentTypeFieldId)
        .field(GraphQLFieldDefinition.newFieldDefinition()
            .name(FIELD_NAME_ITEM)
            .description("List of items of " + contentTypeFieldId)
            .type(list(repeatType.build())))
        .build();

    graphQLField.type(wrapperType);
}
 
Example 7
Source File: CheckboxFieldFactory.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    graphQLField.type(GraphQLBoolean);
    graphQLField.argument(BOOLEAN_FILTER);
}
 
Example 8
Source File: TimeFieldFactory.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    // Add the timezone field as text
    parentGraphQLType.field(GraphQLFieldDefinition.newFieldDefinition()
        .name(getGraphQLName(graphQLFieldName) + FIELD_SUFFIX_TZ)
        .description("Time Zone for field " + contentTypeFieldId)
        .type(GraphQLString)
        .argument(TEXT_FILTER));

    // Add the original according to the suffix
    setTypeFromFieldName(contentTypeFieldId, graphQLField);
}
 
Example 9
Source File: GraphQLSchemaBuilder.java    From graphql-jpa with MIT License 5 votes vote down vote up
GraphQLObjectType getQueryType() {
    GraphQLObjectType.Builder queryType = GraphQLObjectType.newObject().name("QueryType_JPA").description("All encompassing schema for this JPA environment");
    queryType.fields(entityManager.getMetamodel().getEntities().stream().filter(this::isNotIgnored).map(this::getQueryFieldDefinition).collect(Collectors.toList()));
    queryType.fields(entityManager.getMetamodel().getEntities().stream().filter(this::isNotIgnored).map(this::getQueryFieldPageableDefinition).collect(Collectors.toList()));
    queryType.fields(entityManager.getMetamodel().getEmbeddables().stream().filter(this::isNotIgnored).map(this::getQueryEmbeddedFieldDefinition).collect(Collectors.toList()));

    return queryType.build();
}
 
Example 10
Source File: ObjectTypeMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLObjectType toGraphQLType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLObjectType.Builder typeBuilder = newObject()
            .name(typeName)
            .description(buildContext.typeInfoGenerator.generateTypeDescription(javaType, buildContext.messageBundle));

    List<GraphQLFieldDefinition> fields = getFields(typeName, javaType, env);
    fields.forEach(typeBuilder::field);

    List<GraphQLNamedOutputType> interfaces = getInterfaces(javaType, fields, env);
    interfaces.forEach(inter -> {
        if (inter instanceof GraphQLInterfaceType) {
            typeBuilder.withInterface((GraphQLInterfaceType) inter);
        } else {
            typeBuilder.withInterface((GraphQLTypeReference) inter);
        }
    });

    typeBuilder.withDirective(Directives.mappedType(javaType));
    buildContext.directiveBuilder.buildObjectTypeDirectives(javaType, buildContext.directiveBuilderParams()).forEach(directive ->
            typeBuilder.withDirective(env.operationMapper.toGraphQLDirective(directive, buildContext)));
    typeBuilder.comparatorRegistry(buildContext.comparatorRegistry(javaType));

    GraphQLObjectType type = typeBuilder.build();
    interfaces.forEach(inter -> buildContext.typeRegistry.registerCovariantType(inter.getName(), javaType, type));
    return type;
}
 
Example 11
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private void createGraphQLObjectType(Type type) {
    GraphQLObjectType.Builder objectTypeBuilder = GraphQLObjectType.newObject()
            .name(type.getName())
            .description(type.getDescription());

    // Fields
    if (type.hasFields()) {
        objectTypeBuilder = objectTypeBuilder
                .fields(createGraphQLFieldDefinitionsFromFields(type.getName(), type.getFields()));
    }

    // Operations
    if (type.hasOperations()) {
        for (Operation operation : type.getOperations()) {
            GraphQLFieldDefinition graphQLFieldDefinition = createGraphQLFieldDefinitionFromOperation(type.getName(),
                    operation);
            objectTypeBuilder = objectTypeBuilder.field(graphQLFieldDefinition);
        }
    }

    // Interfaces
    if (type.hasInterfaces()) {
        Set<Reference> interfaces = type.getInterfaces();
        for (Reference i : interfaces) {
            if (interfaceMap.containsKey(i.getClassName())) {
                GraphQLInterfaceType graphQLInterfaceType = interfaceMap.get(i.getClassName());
                objectTypeBuilder = objectTypeBuilder.withInterface(graphQLInterfaceType);
            }
        }
    }

    GraphQLObjectType graphQLObjectType = objectTypeBuilder.build();
    typeMap.put(type.getClassName(), graphQLObjectType);

    // Register this output for interface type resolving
    InterfaceOutputRegistry.register(type, graphQLObjectType);
}
 
Example 12
Source File: SchemaBundle.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
public GraphQLSchema toSchema() {
  Map<String, ? extends Function<String, Object>> nodeDataFetchers =
      nodeDataFetchers().stream()
          .collect(Collectors.toMap(e -> e.getClassName(), Function.identity()));

  GraphQLObjectType.Builder queryType = newObject().name("QueryType").fields(queryFields());

  ProtoRegistry protoRegistry =
      ProtoRegistry.newBuilder()
          .setSchemaOptions(schemaOptions())
          .addAll(fileDescriptors())
          .add(modifications())
          .build();

  if (protoRegistry.hasRelayNode()) {
    queryType.field(
        new Relay()
            .nodeField(
                protoRegistry.getRelayNode(),
                environment -> {
                  String id = environment.getArgument("id");
                  Relay.ResolvedGlobalId resolvedGlobalId = new Relay().fromGlobalId(id);
                  Function<String, ?> stringFunction =
                      nodeDataFetchers.get(resolvedGlobalId.getType());
                  if (stringFunction == null) {
                    throw new RuntimeException(
                        String.format(
                            "Relay Node fetcher not implemented for type=%s",
                            resolvedGlobalId.getType()));
                  }
                  return stringFunction.apply(resolvedGlobalId.getId());
                }));
  }

  if (mutationFields().isEmpty()) {
    return GraphQLSchema.newSchema()
        .query(queryType)
        .additionalTypes(protoRegistry.listTypes())
        .build();
  }
  GraphQLObjectType mutationType =
      newObject().name("MutationType").fields(mutationFields()).build();
  return GraphQLSchema.newSchema()
      .query(queryType)
      .mutation(mutationType)
      .additionalTypes(protoRegistry.listTypes())
      .build();
}
 
Example 13
Source File: SchemaCustomizer.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Updates the root type & code registry with the custom fields & fetchers
 * @param rootTypeName the name of the root type
 * @param rootTypeBuilder the root type
 * @param codeRegistry the code registry
 */
protected void apply(String rootTypeName, GraphQLObjectType.Builder rootTypeBuilder,
                  GraphQLCodeRegistry.Builder codeRegistry, Map<String, GraphQLObjectType.Builder> types) {
    customFields.forEach(builder -> {
        String fieldName = builder.field.build().getName();
        if (StringUtils.isEmpty(builder.typeName)) {
            // Add a top level field
            logger.debug("Adding custom field & fetcher {}", fieldName);
            if (rootTypeBuilder.hasField(fieldName)) {
                throw new IllegalArgumentException(
                    String.format("GraphQL schema already contains a field '%s'", fieldName));
            }
            rootTypeBuilder.field(builder.field);
            codeRegistry.dataFetcher(coordinates(rootTypeName, fieldName), ConverterDataFetcher.of(builder.fetcher));
        } else {
            // Add a field to a specific type
            if (!types.containsKey(builder.typeName)) {
                throw new IllegalArgumentException(
                    String.format("GraphQL schema does not contain a type '%s'", builder.typeName));
            } else if (types.get(builder.typeName).hasField(fieldName)) {
                throw new IllegalArgumentException(
                    String.format("GraphQL schema already contains a field '%s.%s'", builder.typeName, fieldName));
            }
            logger.debug("Adding custom field & fetcher {}.{}", builder.typeName, fieldName);
            types.get(builder.typeName).field(builder.field);
            codeRegistry.dataFetcher(coordinates(builder.typeName, fieldName),
                    ConverterDataFetcher.of(builder.fetcher));
        }

    });

    fetchers.forEach(builder -> {
        logger.debug("Adding custom fetcher for {}/{}", builder.typeName, builder.fieldName);
        codeRegistry.dataFetcher(coordinates(builder.typeName, builder.fieldName),
                ConverterDataFetcher.of(builder.dataFetcher));
    });
    resolvers.forEach(builder -> {
        logger.debug("Adding custom resolver for {}", builder.typeName);
        codeRegistry.typeResolver(builder.typeName, builder.resolver);
    });
}
 
Example 14
Source File: CheckboxGroupFieldFactory.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    String datasourceName = XmlUtils.selectSingleNodeValue(contentTypeField, datasourceNameXPath);
    String datasourceSettings = XmlUtils.selectSingleNodeValue(
            contentTypeDefinition, String.format(datasourceSettingsXPathFormat, datasourceName));
    String datasourceType = null;
    String datasourceSuffix = null;

    try {
        if(StringUtils.isNotEmpty(datasourceSettings)) {
            List<Map<String, Object>> typeSetting = objectMapper.readValue(datasourceSettings, List.class);
            Optional<Map<String, Object>> selectedType =
                typeSetting.stream()
                           .filter(s -> (Boolean)s.get(FIELD_NAME_SELECTED)).findFirst();
            if (selectedType.isPresent()) {
                datasourceType = selectedType.get().get(FIELD_NAME_VALUE).toString();
                datasourceSuffix = StringUtils.substringAfter(datasourceType, FIELD_SEPARATOR);
            }
        }
    } catch (IOException e) {
        logger.warn("Error checking data source type for '{}'", contentTypeFieldId);
    }

    String valueKey = FIELD_NAME_VALUE;
    if (StringUtils.isNotEmpty(datasourceSuffix)) {
        valueKey += FIELD_SEPARATOR + datasourceSuffix + FIELD_SUFFIX_MULTIVALUE;
    }

    GraphQLFieldDefinition.Builder valueField = GraphQLFieldDefinition.newFieldDefinition()
        .name(valueKey)
        .description("The value of the item");

    if (StringUtils.isNotEmpty(datasourceType)) {
        setTypeFromFieldName(datasourceType, valueField);
    } else {
        valueField.type(GraphQLString);
        valueField.argument(TEXT_FILTER);
    }

    GraphQLObjectType itemType = GraphQLObjectType.newObject()
        .name(parentGraphQLTypeName + FIELD_SEPARATOR + graphQLFieldName + FIELD_SUFFIX_ITEM)
        .description("Item for field " + contentTypeFieldId)
        .field(GraphQLFieldDefinition.newFieldDefinition()
            .name(FIELD_NAME_KEY)
            .description("The key of the item")
            .type(GraphQLString)
            .argument(TEXT_FILTER))
        .field(valueField)
        .build();

    GraphQLObjectType itemWrapper = GraphQLObjectType.newObject()
        .name(parentGraphQLTypeName + FIELD_SEPARATOR + graphQLFieldName + FIELD_SUFFIX_ITEMS)
        .description("Wrapper for field " + contentTypeFieldId)
        .field(GraphQLFieldDefinition.newFieldDefinition()
            .name(FIELD_NAME_ITEM)
            .description("List of items for field " + contentTypeFieldId)
            .type(list(itemType)))
        .build();

    graphQLField.type(itemWrapper);
}
 
Example 15
Source File: Type.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
GraphQLObjectType.Builder toBuilder(GraphQLObjectType input) {
  return newObject()
      .name(input.getName())
      .description(input.getDescription())
      .fields(input.getFieldDefinitions());
}
 
Example 16
Source File: NodeSelectorFieldFactory.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    boolean disableFlattening = BooleanUtils.toBoolean(
            XmlUtils.selectSingleNodeValue(contentTypeField, disableFlatteningXPath));

    if (disableFlattening) {
        // Flattening is disabled, so use the generic item include type
        logger.debug("Flattening is disabled for node selector '{}'. Won't generate additional schema " +
            "types and fields for its items", graphQLFieldName);

        graphQLField.type(ITEM_INCLUDE_WRAPPER_TYPE);
        return;
    }

    String datasourceName = XmlUtils.selectSingleNodeValue(contentTypeField, datasourceNameXPath);
    String itemType = XmlUtils.selectSingleNodeValue(
        contentTypeDefinition, String.format(datasourceItemTypeXPathFormat, datasourceName));
    String itemGraphQLType = StringUtils.isNotEmpty(itemType)? getGraphQLName(itemType) : null;

    if (StringUtils.isEmpty(itemGraphQLType)) {
        // If there is no item content-type set in the datasource, use the generic item include type
        logger.debug("No specific item type found for node selector '{}'. Won't generate additional schema " +
            "types and fields for its items", graphQLFieldName);

        graphQLField.type(CONTENT_INCLUDE_WRAPPER_TYPE);
    } else {
        // If there is an item content-type, then create a specific GraphQL type for it
        logger.debug("Item type found for node selector '{}': '{}'. Generating additional schema types and " +
            "fields for the items...", itemGraphQLType, graphQLFieldName);

        GraphQLObjectType flattenedType = GraphQLObjectType.newObject()
            .name(parentGraphQLTypeName + FIELD_SEPARATOR + graphQLFieldName + "_flattened_item")
            .description("Contains the data from another item in the site")
            .field(GraphQLFieldDefinition.newFieldDefinition()
                .name(FIELD_NAME_VALUE)
                .description("The name of the item")
                .type(nonNull(GraphQLString)))
            .field(GraphQLFieldDefinition.newFieldDefinition()
                .name(FIELD_NAME_KEY)
                .description("The path of the item")
                .type(nonNull(GraphQLString)))
            .field(GraphQLFieldDefinition.newFieldDefinition()
                .name(FIELD_NAME_COMPONENT)
                .description("The content of the item")
                .type(GraphQLTypeReference.typeRef(itemGraphQLType)))
            .build();

        GraphQLObjectType wrapperType = GraphQLObjectType.newObject()
            .name(parentGraphQLTypeName + FIELD_SEPARATOR + graphQLFieldName + FIELD_SUFFIX_ITEMS)
            .description("Wrapper for flattened items")
            .field(GraphQLFieldDefinition.newFieldDefinition()
                .name(FIELD_NAME_ITEM)
                .description("List of flattened items")
                .type(list(nonNull(flattenedType))))
            .build();

        graphQLField.type(wrapperType);
    }
}
 
Example 17
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 18
Source File: GraphQLFieldFactory.java    From engine with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Adds all the required objects for a content-type field to a {@link GraphQLObjectType}
 *
 * @param contentTypeDefinition the XML document with the content type definition
 * @param contentTypeField      the XML node with the content-type field
 * @param contentTypeFieldId    the content-type field ID
 * @param parentGraphQLTypeName the field's parent GraphQL type name
 * @param parentGraphQLType     the field's parent {@link GraphQLObjectType}
 * @param graphQLFieldName      the field's GraphQL-friendly name
 * @param graphQLField          the field's {@link GraphQLFieldDefinition}
 */
void createField(Document contentTypeDefinition, Node contentTypeField, String contentTypeFieldId,
                 String parentGraphQLTypeName, GraphQLObjectType.Builder parentGraphQLType,
                 String graphQLFieldName, GraphQLFieldDefinition.Builder graphQLField);
 
Example 19
Source File: GraphQLTypeFactory.java    From engine with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Creates a GraphQL type for the given content-type and adds a field in the root type
 *
 * @param contentTypeDefinition the XML definition of the content-type
 * @param rootGraphQLType       the {@link GraphQLObjectType} for the root query
 * @param codeRegistry          the {@link GraphQLCodeRegistry} to add {@link graphql.schema.DataFetcher} for new
 *                              fields
 * @param siteTypes             all content-type related types
 * @param dataFetcher           the {@link DataFetcher} to use for the new fields
 */
void createType(Item contentTypeDefinition, GraphQLObjectType.Builder rootGraphQLType,
                GraphQLCodeRegistry.Builder codeRegistry, DataFetcher<?> dataFetcher,
                Map<String, GraphQLObjectType.Builder> siteTypes);
 
Example 20
Source File: GraphQLTypeFactory.java    From engine with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Creates a GraphQL field for the given content-type field and adds it to the given GraphQL type
 *
 * @param contentTypeDefinition the XML definition of the content-type
 * @param contentTypeField      the XML node for the content-type field
 * @param parentGraphQLTypeName the field's parent GraphQL type name
 * @param parentGraphQLType     the field's parent {@link GraphQLObjectType}
 */
void createField(Document contentTypeDefinition, Node contentTypeField, String parentGraphQLTypeName,
                 GraphQLObjectType.Builder parentGraphQLType);