graphql.schema.GraphQLTypeReference Java Examples

The following examples show how to use graphql.schema.GraphQLTypeReference. 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 createGraphQLInterfaceType(InterfaceType interfaceType) {
    GraphQLInterfaceType.Builder interfaceTypeBuilder = GraphQLInterfaceType.newInterface()
            .name(interfaceType.getName())
            .description(interfaceType.getDescription());

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

    // Interfaces
    if (interfaceType.hasInterfaces()) {
        Set<Reference> interfaces = interfaceType.getInterfaces();
        for (Reference i : interfaces) {
            interfaceTypeBuilder = interfaceTypeBuilder.withInterface(GraphQLTypeReference.typeRef(i.getName()));
        }
    }

    GraphQLInterfaceType graphQLInterfaceType = interfaceTypeBuilder.build();
    // To resolve the concrete class
    codeRegistryBuilder.typeResolver(graphQLInterfaceType,
            new InterfaceResolver(interfaceType));

    interfaceMap.put(interfaceType.getClassName(), graphQLInterfaceType);
}
 
Example #2
Source File: TypeRegistry.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
void resolveTypeReferences(Map<String, GraphQLNamedType> resolvedTypes) {
    for (Map<String, MappedType> covariantTypes : this.covariantOutputTypes.values()) {
        Set<String> toRemove = new HashSet<>();
        for (Map.Entry<String, MappedType> entry : covariantTypes.entrySet()) {
            if (entry.getValue().graphQLType instanceof GraphQLTypeReference) {
                GraphQLOutputType resolvedType = (GraphQLNamedOutputType) resolvedTypes.get(entry.getKey());
                if (resolvedType != null) {
                    entry.setValue(new MappedType(entry.getValue().javaType, resolvedType));
                } else {
                    log.warn("Type reference " + entry.getKey() + " could not be replaced correctly. " +
                            "This can occur when the schema generator is initialized with " +
                            "additional types not built by GraphQL SPQR. If this type implements " +
                            "Node, in some edge cases it may end up not exposed via the 'node' query.");
                    //the edge case is when the primary resolver returns an interface or a union and not the node type directly
                    toRemove.add(entry.getKey());
                }
            }
        }
        toRemove.forEach(covariantTypes::remove);
        covariantTypes.replaceAll((typeName, mapped) -> mapped.graphQLType instanceof GraphQLTypeReference
                ? new MappedType(mapped.javaType, (GraphQLOutputType) resolvedTypes.get(typeName)) : mapped);
    }
}
 
Example #3
Source File: MapToListTypeAdapter.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private GraphQLInputType mapEntry(GraphQLInputType keyType, GraphQLInputType valueType, BuildContext buildContext) {
    String typeName = "mapEntry_" + getTypeName(keyType) + "_" + getTypeName(valueType) + "_input";
    if (buildContext.typeCache.contains(typeName)) {
        return new GraphQLTypeReference(typeName);
    }
    buildContext.typeCache.register(typeName);

    return newInputObject()
            .name(typeName)
            .description("Map entry input")
            .field(newInputObjectField()
                    .name("key")
                    .description("Map key input")
                    .type(keyType)
                    .build())
            .field(newInputObjectField()
                    .name("value")
                    .description("Map value input")
                    .type(valueType)
                    .build())
            .build();
}
 
Example #4
Source File: MapToListTypeAdapter.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private GraphQLOutputType mapEntry(GraphQLOutputType keyType, GraphQLOutputType valueType, BuildContext buildContext) {
    String typeName = "mapEntry_" + getTypeName(keyType) + "_" + getTypeName(valueType);
    if (buildContext.typeCache.contains(typeName)) {
        return new GraphQLTypeReference(typeName);
    }
    buildContext.typeCache.register(typeName);

    return newObject()
            .name(typeName)
            .description("Map entry")
            .field(newFieldDefinition()
                    .name("key")
                    .description("Map key")
                    .type(keyType)
                    .build())
            .field(newFieldDefinition()
                    .name("value")
                    .description("Map value")
                    .type(valueType)
                    .build())
            .build();
}
 
Example #5
Source File: PageMapper.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
public GraphQLOutputType toGraphQLType(AnnotatedType javaType, Set<Class<? extends TypeMapper>> mappersToSkip, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    AnnotatedType edgeType = GenericTypeReflector.getTypeParameter(javaType, Connection.class.getTypeParameters()[0]);
    AnnotatedType nodeType = GenericTypeReflector.getTypeParameter(edgeType, Edge.class.getTypeParameters()[0]);
    String connectionName = buildContext.typeInfoGenerator.generateTypeName(nodeType, buildContext.messageBundle) + "Connection";
    if (buildContext.typeCache.contains(connectionName)) {
        return new GraphQLTypeReference(connectionName);
    }
    buildContext.typeCache.register(connectionName);
    GraphQLOutputType type = env.operationMapper.toGraphQLType(nodeType, env);
    GraphQLNamedType unwrapped = GraphQLUtils.unwrap(type);
    String baseName = type instanceof GraphQLList ? unwrapped.getName() + "List" : unwrapped.getName();
    List<GraphQLFieldDefinition> edgeFields = getFields(baseName + "Edge", edgeType, env).stream()
            .filter(field -> !GraphQLUtils.isRelayEdgeField(field))
            .collect(Collectors.toList());
    GraphQLObjectType edge = buildContext.relay.edgeType(baseName, type, null, edgeFields);
    List<GraphQLFieldDefinition> connectionFields = getFields(baseName + "Connection", javaType, env).stream()
            .filter(field -> !GraphQLUtils.isRelayConnectionField(field))
            .collect(Collectors.toList());
    buildContext.typeRegistry.getDiscoveredTypes().add(Relay.pageInfoType);
    return buildContext.relay.connectionType(baseName, edge, connectionFields);
}
 
Example #6
Source File: CachingMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLOutputType toGraphQLType(AnnotatedType javaType, Set<Class<? extends TypeMapper>> mappersToSkip, TypeMappingEnvironment env) {
    String typeName = getTypeName(javaType, env.buildContext);
    if (env.buildContext.typeCache.contains(typeName)) {
        return new GraphQLTypeReference(typeName);
    }
    env.buildContext.typeCache.register(typeName);
    return toGraphQLType(typeName, javaType, env);
}
 
Example #7
Source File: GraphQLSchemaGenerator.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private boolean isRealType(GraphQLNamedType type) {
    // Reject introspection types
    return !(GraphQLUtils.isIntrospectionType(type)
            // Reject quasi-types
            || type instanceof GraphQLTypeReference
            || type instanceof GraphQLArgument
            || type instanceof GraphQLDirective
            // Reject root types
            || type.getName().equals(messageBundle.interpolate(queryRoot))
            || type.getName().equals(messageBundle.interpolate(mutationRoot))
            || type.getName().equals(messageBundle.interpolate(subscriptionRoot)));
}
 
Example #8
Source File: TypeRegistry.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public void registerCovariantType(String compositeTypeName, AnnotatedType javaSubType, GraphQLNamedOutputType subType) {
    this.covariantOutputTypes.putIfAbsent(compositeTypeName, new ConcurrentHashMap<>());
    Map<String, MappedType> covariantTypes = this.covariantOutputTypes.get(compositeTypeName);
    //never overwrite an exact type with a reference
    if (subType instanceof GraphQLObjectType || covariantTypes.get(subType.getName()) == null || covariantTypes.get(subType.getName()).graphQLType instanceof GraphQLTypeReference) {
        covariantTypes.put(subType.getName(), new MappedType(javaSubType, subType));
    }
}
 
Example #9
Source File: MappedType.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
MappedType(AnnotatedType javaType, GraphQLOutputType graphQLType) {
    if (!(graphQLType instanceof GraphQLTypeReference || graphQLType instanceof GraphQLObjectType)) {
        throw new IllegalArgumentException("Implementation types can only be object types or references to object types");
    }
    this.rawJavaType = ClassUtils.getRawType(javaType.getType());
    this.javaType = javaType;
    this.graphQLType = graphQLType;
}
 
Example #10
Source File: TypeCache.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
GraphQLType resolveType(String typeName) {
    GraphQLType resolved = knownTypes.get(typeName);
    if (resolved instanceof GraphQLTypeReference) {
        throw new IllegalStateException("Type " + typeName + " is not yet resolvable");
    }
    return resolved;
}
 
Example #11
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 #12
Source File: CachingMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLInputType toGraphQLInputType(AnnotatedType javaType, Set<Class<? extends TypeMapper>> mappersToSkip, TypeMappingEnvironment env) {
    String typeName = getInputTypeName(javaType, env.buildContext);
    if (env.buildContext.typeCache.contains(typeName)) {
        return new GraphQLTypeReference(typeName);
    }
    env.buildContext.typeCache.register(typeName);
    return toGraphQLInputType(typeName, javaType, env);
}
 
Example #13
Source File: _Entity.java    From federation-jvm with MIT License 5 votes vote down vote up
static GraphQLFieldDefinition field(@NotNull Set<String> typeNames) {
    return newFieldDefinition()
            .name(fieldName)
            .argument(newArgument()
                    .name(argumentName)
                    .type(new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(new GraphQLTypeReference(_Any.typeName)))))
                    .build())
            .type(new GraphQLNonNull(
                            new GraphQLList(
                                    GraphQLUnionType.newUnionType()
                                            .name(typeName)
                                            .possibleTypes(typeNames.stream()
                                                    .map(GraphQLTypeReference::new)
                                                    .toArray(GraphQLTypeReference[]::new))
                                            .build()
                            )
                    )
            )
            .build();
}
 
Example #14
Source File: GqlInputConverter.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
private static GraphQLType getFieldType(FieldDescriptor field, SchemaOptions schemaOptions) {
  if (field.getType() == FieldDescriptor.Type.MESSAGE
      || field.getType() == FieldDescriptor.Type.GROUP) {
    return new GraphQLTypeReference(getReferenceName(field.getMessageType()));
  }
  if (field.getType() == FieldDescriptor.Type.ENUM) {
    return new GraphQLTypeReference(ProtoToGql.getReferenceName(field.getEnumType()));
  }
  GraphQLType type = ProtoToGql.convertType(field, schemaOptions);
  if (type instanceof GraphQLList) {
    return ((GraphQLList) type).getWrappedType();
  }
  return type;
}
 
Example #15
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private GraphQLInputType referenceGraphQLInputType(Field field) {
    Reference reference = getCorrectFieldReference(field);
    ReferenceType type = reference.getType();
    String className = reference.getClassName();
    String name = reference.getName();
    switch (type) {
        case SCALAR:
            return getCorrectScalarType(reference);
        case ENUM:
            return enumMap.get(className);
        default:
            return GraphQLTypeReference.typeRef(name);
    }
}
 
Example #16
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private GraphQLOutputType referenceGraphQLOutputType(Field field) {
    Reference reference = getCorrectFieldReference(field);
    ReferenceType type = reference.getType();
    String className = reference.getClassName();
    String name = reference.getName();
    switch (type) {
        case SCALAR:
            return getCorrectScalarType(reference);
        case ENUM:
            return enumMap.get(className);
        default:
            return GraphQLTypeReference.typeRef(name);
    }
}
 
Example #17
Source File: TypeGenerator.java    From graphql-java-type-generator with MIT License 4 votes vote down vote up
/**
 * An internal, unchanging impl.
 * @param object
 * @param genericType
 * @param typeKind
 * @return
 */
protected final GraphQLType getType(Object object,
        Type genericType, TypeKind typeKind) {
    logger.debug("{} object is [{}]", typeKind, object);
    
    //short circuit if it's a primitive type or some other user defined default
    GraphQLType defaultType = getDefaultType(object, typeKind);
    if (defaultType != null) {
        return defaultType;
    }
    
    
    String typeName = getGraphQLTypeName(object);
    if (typeName == null) {
        logger.debug("TypeName was null for object [{}]. "
                + "Type will attempt to be built but not placed in the TypeRepository", object);
        return generateType(object, typeKind);
    }
    
    
    //this check must come before generated*Types.get
    //necessary for synchronicity to avoid duplicate object creations
    Set<String> typesBeingBuilt = getContext().getTypesBeingBuilt();
    if (typesBeingBuilt.contains(typeName)) {
        logger.debug("Using a reference to: [{}]", typeName);
        if (TypeKind.OBJECT.equals(typeKind)) {
            return new GraphQLTypeReference(typeName);
        }
        logger.error("While constructing type, using a reference to: [{}]", typeName);
        throw new RuntimeException("Cannot put type-cycles into input or interface types, "
                + "there is no GraphQLTypeReference");
    }
    
    
    GraphQLType prevType = getTypeRepository().getGeneratedType(typeName, typeKind);
    if (prevType != null) {
        return prevType;
    }
    
    
    typesBeingBuilt.add(typeName);
    try {
        GraphQLType type = generateType(object, typeKind);
        if (getTypeRepository() != null && type != null) {
            getTypeRepository().registerType(typeName, type, typeKind);
        }
        return type;
    }
    catch (RuntimeException e) {
        logger.warn("Failed to generate type named {} with kind {}", typeName, typeKind);
        logger.debug("Failed to generate type, exception is ", e);
        throw e;
    }
    finally {
        typesBeingBuilt.remove(typeName);
    }
}
 
Example #18
Source File: SchemaDefinitionReader.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
protected final GraphQLTypeReference getInputTypeReference(Descriptor descriptor) {
  referencedDescriptors.add(descriptor);
  return new GraphQLTypeReference(GqlInputConverter.getReferenceName(descriptor));
}
 
Example #19
Source File: GqlInputConverter.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
private static GraphQLInputType getInputTypeReference(Descriptor descriptor) {
  return new GraphQLTypeReference(getReferenceName(descriptor));
}
 
Example #20
Source File: ProtoToGql.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
/** Returns a reference to the GraphQL type corresponding to the supplied proto. */
static GraphQLTypeReference getReference(GenericDescriptor descriptor) {
  return new GraphQLTypeReference(getReferenceName(descriptor));
}
 
Example #21
Source File: UnionMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("WeakerAccess")
protected GraphQLOutputType toGraphQLUnion(String name, String description, AnnotatedType javaType,
                                           List<AnnotatedType> possibleJavaTypes, TypeMappingEnvironment env) {

    BuildContext buildContext = env.buildContext;
    OperationMapper operationMapper = env.operationMapper;

    if (buildContext.typeCache.contains(name)) {
        return new GraphQLTypeReference(name);
    }
    buildContext.typeCache.register(name);
    GraphQLUnionType.Builder builder = newUnionType()
            .name(name)
            .description(description);

    Set<String> seen = new HashSet<>(possibleJavaTypes.size());

    possibleJavaTypes.forEach(possibleJavaType -> {
        GraphQLNamedOutputType possibleType = (GraphQLNamedOutputType) operationMapper.toGraphQLType(possibleJavaType, env);
        if (!seen.add(possibleType.getName())) {
            throw new TypeMappingException("Duplicate possible type " + possibleType.getName() + " for union " + name);
        }

        if (possibleType instanceof GraphQLObjectType) {
            builder.possibleType((GraphQLObjectType) possibleType);
        } else if (possibleType instanceof GraphQLTypeReference) {
            builder.possibleType((GraphQLTypeReference) possibleType);
        } else {
            throw new TypeMappingException(possibleType.getClass().getSimpleName() +
                    " is not a valid GraphQL union member. Only object types can be unionized.");
        }

        buildContext.typeRegistry.registerCovariantType(name, possibleJavaType, possibleType);
    });

    builder.withDirective(Directives.mappedType(javaType));
    buildContext.directiveBuilder.buildUnionTypeDirectives(javaType, buildContext.directiveBuilderParams()).forEach(directive ->
            builder.withDirective(operationMapper.toGraphQLDirective(directive, buildContext)));
    builder.comparatorRegistry(buildContext.comparatorRegistry(javaType));

    GraphQLUnionType union = builder.build();
    buildContext.codeRegistry.typeResolver(union, buildContext.typeResolver);
    return union;
}
 
Example #22
Source File: SchemaModule.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
protected final GraphQLTypeReference getInputTypeReference(Descriptor descriptor) {
  return definition.getInputTypeReference(descriptor);
}
 
Example #23
Source File: TypeCache.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
void completeType(GraphQLOutputType type) {
    GraphQLNamedType namedType = GraphQLUtils.unwrap(type);
    if (!(namedType instanceof GraphQLTypeReference)) {
        knownTypes.put(namedType.getName(), namedType);
    }
}
 
Example #24
Source File: Types.java    From spring-boot-starter-graphql with Apache License 2.0 4 votes vote down vote up
public static GraphQLTypeReference ref (String aName) {
  return new GraphQLTypeReference(aName);
}
 
Example #25
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 #26
Source File: SchemaDefinitionReader.java    From rejoiner with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a reference to the GraphQL type corresponding to the supplied proto.
 *
 * <p>All types in the proto are made available to be included in the GraphQL schema.
 */
protected final GraphQLTypeReference getTypeReference(Descriptor descriptor) {
  referencedDescriptors.add(descriptor);
  return ProtoToGql.getReference(descriptor);
}
 
Example #27
Source File: SchemaModule.java    From rejoiner with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a reference to the GraphQL type corresponding to the supplied proto.
 *
 * <p>All types in the proto are made available to be included in the GraphQL schema.
 */
protected final GraphQLTypeReference getTypeReference(Descriptor descriptor) {
  return definition.getTypeReference(descriptor);
}