graphql.schema.GraphQLNamedType Java Examples

The following examples show how to use graphql.schema.GraphQLNamedType. 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: FederationSdlPrinter.java    From federation-jvm with MIT License 6 votes vote down vote up
private Options(boolean includeIntrospectionTypes,
                boolean includeScalars,
                boolean includeExtendedScalars,
                boolean includeSchemaDefinition,
                boolean useAstDefinitions,
                boolean descriptionsAsHashComments,
                Predicate<GraphQLDirective> includeDirective,
                Predicate<GraphQLDirective> includeDirectiveDefinition,
                Predicate<GraphQLNamedType> includeTypeDefinition,
                GraphqlTypeComparatorRegistry comparatorRegistry) {
    this.includeIntrospectionTypes = includeIntrospectionTypes;
    this.includeScalars = includeScalars;
    this.includeExtendedScalars = includeExtendedScalars;
    this.includeSchemaDefinition = includeSchemaDefinition;
    this.includeDirective = includeDirective;
    this.includeDirectiveDefinition = includeDirectiveDefinition;
    this.includeTypeDefinition = includeTypeDefinition;
    this.useAstDefinitions = useAstDefinitions;
    this.descriptionsAsHashComments = descriptionsAsHashComments;
    this.comparatorRegistry = comparatorRegistry;
}
 
Example #2
Source File: TypeRegistry.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
public TypeRegistry(Collection<GraphQLNamedType> knownTypes) {
    //extract known interface implementations
    knownTypes.stream()
            .filter(type -> type instanceof GraphQLObjectType && Directives.isMappedType(type))
            .map(type -> (GraphQLObjectType) type)
            .forEach(obj -> obj.getInterfaces().forEach(
                    inter -> registerCovariantType(inter.getName(), Directives.getMappedType(obj), obj)));

    //extract known union members
    knownTypes.stream()
            .filter(type -> type instanceof GraphQLUnionType)
            .map(type -> (GraphQLUnionType) type)
            .forEach(union -> union.getTypes().stream()
                    .filter(type -> type instanceof GraphQLObjectType && Directives.isMappedType(type))
                    .map(type -> (GraphQLObjectType) type)
                    .forEach(obj -> registerCovariantType(union.getName(), Directives.getMappedType(obj), obj)));
}
 
Example #3
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 #4
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 #5
Source File: ResolutionEnvironment.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
public ResolutionEnvironment(Resolver resolver, DataFetchingEnvironment env, ValueMapper valueMapper, GlobalEnvironment globalEnvironment,
                             ConverterRegistry converters, DerivedTypeRegistry derivedTypes) {

    this.context = env.getSource();
    this.rootContext = env.getContext();
    this.resolver = resolver;
    this.valueMapper = valueMapper;
    this.globalEnvironment = globalEnvironment;
    this.converters = converters;
    this.fieldType = env.getFieldType();
    this.parentType = (GraphQLNamedType) env.getParentType();
    this.graphQLSchema = env.getGraphQLSchema();
    this.dataFetchingEnvironment = env;
    this.derivedTypes = derivedTypes;
    this.arguments = new HashMap<>();
}
 
Example #6
Source File: FederationTest.java    From federation-jvm with MIT License 6 votes vote down vote up
@Test
void testInterfacesAreCovered() {
    final RuntimeWiring wiring = RuntimeWiring.newRuntimeWiring()
            .type(TypeRuntimeWiring.newTypeWiring("Product")
                    .typeResolver(env -> null)
                    .build())
            .build();

    final GraphQLSchema transformed = Federation.transform(interfacesSDL, wiring)
            .resolveEntityType(env -> null)
            .fetchEntities(environment -> null)
            .build();

    final GraphQLUnionType entityType = (GraphQLUnionType) transformed.getType(_Entity.typeName);

    final Iterable<String> unionTypes = entityType
            .getTypes()
            .stream()
            .map(GraphQLNamedType::getName)
            .sorted()
            .collect(Collectors.toList());

    assertIterableEquals(Arrays.asList("Book", "Movie", "Page"), unionTypes);
}
 
Example #7
Source File: Validator.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private ValidationResult checkUniqueness(GraphQLType graphQLType, Supplier<AnnotatedType> javaType) {
    if (!(graphQLType instanceof GraphQLNamedType)) {
        return ValidationResult.valid();
    }
    GraphQLNamedType namedType = ((GraphQLNamedType) graphQLType);

    AnnotatedType resolvedType;
    try {
        resolvedType = resolveType(graphQLType, javaType);
    } catch (Exception e) {
        return ValidationResult.invalid(
                String.format("Exception while checking the name uniqueness for %s: %s", namedType.getName(), e.getMessage()));
    }
    mappedTypes.putIfAbsent(namedType.getName(), resolvedType);
    AnnotatedType knownType = mappedTypes.get(namedType.getName());
    if (isMappingAllowed(resolvedType, knownType)) {
        return ValidationResult.valid();
    }
    return ValidationResult.invalid(String.format("Potential type name collision detected: '%s' bound to multiple types:" +
                    " %s (loaded by %s) and %s (loaded by %s)." +
                    " Assign unique names using the appropriate annotations or override the %s." +
                    " For details and solutions see %s." +
                    " If this warning is a false positive, please report it: %s.", namedType.getName(),
            knownType, getLoaderName(knownType), resolvedType, getLoaderName(resolvedType),
            TypeInfoGenerator.class.getSimpleName(), Urls.Errors.NON_UNIQUE_TYPE_NAME, Urls.ISSUES));
}
 
Example #8
Source File: MockDataFetchEnvironment.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
public static DataFetchingEnvironment myFastQueryDfe(String typeName, String fieldName, String operationName,
        String executionId) {
    GraphQLNamedType query = mock(GraphQLNamedType.class);
    when(query.getName()).thenReturn(typeName);

    Field field = mock(Field.class);
    when(field.getName()).thenReturn(fieldName);

    OperationDefinition operationDefinition = mock(OperationDefinition.class);
    when(operationDefinition.getName()).thenReturn(operationName);

    ExecutionPath executionPath = mock(ExecutionPath.class);
    when(executionPath.toString()).thenReturn("/" + typeName + "/" + fieldName);
    ExecutionStepInfo executionStepInfo = mock(ExecutionStepInfo.class);
    when(executionStepInfo.getPath()).thenReturn(executionPath);

    DataFetchingEnvironment dfe = mock(DataFetchingEnvironment.class);
    when(dfe.getParentType()).thenReturn(query);
    when(dfe.getField()).thenReturn(field);
    when(dfe.getOperationDefinition()).thenReturn(operationDefinition);
    when(dfe.getExecutionStepInfo()).thenReturn(executionStepInfo);
    when(dfe.getExecutionId()).thenReturn(ExecutionId.from(executionId));

    return dfe;
}
 
Example #9
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 #10
Source File: Validator.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
Validator(GlobalEnvironment environment, TypeMapperRegistry mappers, Collection<GraphQLNamedType> knownTypes, Comparator<AnnotatedType> typeComparator) {
    this.environment = environment;
    this.mappers = mappers;
    this.typeComparator = typeComparator;
    this.mappedTypes = knownTypes.stream()
            .filter(Directives::isMappedType)
            .collect(Collectors.toMap(GraphQLNamedType::getName, type -> ClassUtils.normalize(Directives.getMappedType(type))));
}
 
Example #11
Source File: GqlInputConverterTest.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Test
public void inputConverterShouldCreateArgumentForMessagesInSameFile() {
  GraphQLArgument argument = GqlInputConverter.createArgument(Proto2.getDescriptor(), "input");
  Truth.assertThat(argument.getName()).isEqualTo("input");
  Truth.assertThat(((GraphQLNamedType) argument.getType()).getName())
      .isEqualTo("Input_javatests_com_google_api_graphql_rejoiner_proto_Proto2");
}
 
Example #12
Source File: GqlInputConverterTest.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Test
public void inputConverterShouldCreateArgument() {
  GraphQLArgument argument = GqlInputConverter.createArgument(Proto1.getDescriptor(), "input");
  Truth.assertThat(argument.getName()).isEqualTo("input");
  Truth.assertThat(((GraphQLNamedType) argument.getType()).getName())
      .isEqualTo("Input_javatests_com_google_api_graphql_rejoiner_proto_Proto1");
}
 
Example #13
Source File: SchemaToProto.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
private static String toType(GraphQLType type) {
  if (type instanceof GraphQLList) {
    return "repeated " + toType(((GraphQLList) type).getWrappedType());
  } else if (type instanceof GraphQLObjectType) {
    return ((GraphQLObjectType) type).getName();
  } else if (type instanceof GraphQLEnumType) {
    return ((GraphQLEnumType) type).getName() + ".Enum";
  } else {
    return TYPE_MAP.get(((GraphQLNamedType) type).getName());
  }
}
 
Example #14
Source File: NameHelper.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
public static String getName(GraphQLType graphQLType) {
    if (graphQLType instanceof GraphQLNamedType) {
        return ((GraphQLNamedType) graphQLType).getName();
    } else if (graphQLType instanceof GraphQLNonNull) {
        return getName(((GraphQLNonNull) graphQLType).getWrappedType());
    } else if (graphQLType instanceof GraphQLList) {
        return getName(((GraphQLList) graphQLType).getWrappedType());
    }
    return EMPTY;
}
 
Example #15
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
/**
 * This can print an in memory GraphQL schema back to a logical schema definition
 *
 * @param schema the schema in play
 * @return the logical schema definition
 */
public String print(GraphQLSchema schema) {
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);

    GraphqlFieldVisibility visibility = schema.getCodeRegistry().getFieldVisibility();

    printer(schema.getClass()).print(out, schema, visibility);

    List<GraphQLType> typesAsList = schema.getAllTypesAsList()
            .stream()
            .sorted(Comparator.comparing(GraphQLNamedType::getName))
            .filter(options.getIncludeTypeDefinition())
            .collect(toList());

    printType(out, typesAsList, GraphQLInterfaceType.class, visibility);
    printType(out, typesAsList, GraphQLUnionType.class, visibility);
    printType(out, typesAsList, GraphQLObjectType.class, visibility);
    printType(out, typesAsList, GraphQLEnumType.class, visibility);
    printType(out, typesAsList, GraphQLScalarType.class, visibility);
    printType(out, typesAsList, GraphQLInputObjectType.class, visibility);

    String result = sw.toString();
    if (result.endsWith("\n\n")) {
        result = result.substring(0, result.length() - 1);
    }
    return result;
}
 
Example #16
Source File: GraphQLUtil.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
public static String getName(GraphQLType graphQLType) {
    if (graphQLType instanceof GraphQLNamedType) {
        return ((GraphQLNamedType) graphQLType).getName();
    }
    return "";
}
 
Example #17
Source File: GraphQLUtils.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public static boolean isIntrospectionType(GraphQLType type) {
    return type instanceof GraphQLNamedType && isIntrospection(name(type));
}
 
Example #18
Source File: GraphQLUtils.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public static GraphQLNamedType unwrap(GraphQLType type) {
    while (type instanceof GraphQLModifiedType) {
        type = ((GraphQLModifiedType) type).getWrappedType();
    }
    return (GraphQLNamedType) type;
}
 
Example #19
Source File: OperationMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
private Map<String, String> getNodeQueriesByType(List<Operation> queries,
                                                 List<GraphQLFieldDefinition> graphQLQueries,
                                                 TypeRegistry typeRegistry, GraphQLInterfaceType node, BuildContext buildContext) {

    Map<String, String> nodeQueriesByType = new HashMap<>();

    for (int i = 0; i < queries.size(); i++) {
        Operation query = queries.get(i);
        GraphQLFieldDefinition graphQLQuery = graphQLQueries.get(i);

        if (graphQLQuery.getArgument(GraphQLId.RELAY_ID_FIELD_NAME) != null
                && GraphQLUtils.isRelayId(graphQLQuery.getArgument(GraphQLId.RELAY_ID_FIELD_NAME))
                && query.getResolver(GraphQLId.RELAY_ID_FIELD_NAME) != null) {

            GraphQLType unwrappedQueryType = GraphQLUtils.unwrapNonNull(graphQLQuery.getType());
            if (unwrappedQueryType instanceof GraphQLNamedType) {
                GraphQLNamedType unwrappedOutput = (GraphQLNamedOutputType) unwrappedQueryType;
                unwrappedQueryType = buildContext.typeCache.resolveType(unwrappedOutput.getName());
                if (unwrappedQueryType instanceof GraphQLObjectType
                        && ((GraphQLObjectType) unwrappedQueryType).getInterfaces().contains(node)) {
                    nodeQueriesByType.put(unwrappedOutput.getName(), query.getName());
                } else if (unwrappedQueryType instanceof GraphQLInterfaceType) {
                    typeRegistry.getOutputTypes(unwrappedOutput.getName()).stream()
                            .map(MappedType::getAsObjectType)
                            .filter(implementation -> implementation.getInterfaces().contains(node))
                            .forEach(nodeType -> nodeQueriesByType.putIfAbsent(nodeType.getName(), query.getName()));  //never override more precise resolvers
                } else if (unwrappedQueryType instanceof GraphQLUnionType) {
                    typeRegistry.getOutputTypes(unwrappedOutput.getName()).stream()
                            .map(MappedType::getAsObjectType)
                            .filter(implementation -> implementation.getInterfaces().contains(node))
                            .filter(Directives::isMappedType)
                            // only register the possible types that can actually be returned from the primary resolver
                            // for interface-unions it is all the possible types but, for inline unions, only one (right?) possible type can match
                            .filter(implementation -> GenericTypeReflector.isSuperType(query.getResolver(GraphQLId.RELAY_ID_FIELD_NAME).getReturnType().getType(), Directives.getMappedType(implementation).getType()))
                            .forEach(nodeType -> nodeQueriesByType.putIfAbsent(nodeType.getName(), query.getName())); //never override more precise resolvers
                }
            }
        }
    }
    return nodeQueriesByType;
}
 
Example #20
Source File: DelegatingTypeResolver.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public GraphQLObjectType getType(TypeResolutionEnvironment env) {
    Object result = env.getObject();
    Class<?> resultType = result.getClass();
    String resultTypeName = typeInfoGenerator.generateTypeName(GenericTypeReflector.annotate(resultType), messageBundle);
    GraphQLNamedType fieldType = (GraphQLNamedType) env.getFieldType();
    String abstractTypeName = this.abstractTypeName != null ? this.abstractTypeName : fieldType.getName();

    //Check if the type is already unambiguous
    List<MappedType> mappedTypes = typeRegistry.getOutputTypes(abstractTypeName, resultType);
    if (mappedTypes.isEmpty()) {
        return (GraphQLObjectType) env.getSchema().getType(resultTypeName);
    }
    if (mappedTypes.size() == 1) {
        return mappedTypes.get(0).getAsObjectType();
    }

    AnnotatedType returnType = Directives.getMappedType(fieldType);
    //Try to find an explicit resolver
    Optional<GraphQLObjectType> resolvedType = Utils.or(
            Optional.ofNullable(returnType != null ? returnType.getAnnotation(GraphQLTypeResolver.class) : null),
            Optional.ofNullable(resultType.getAnnotation(GraphQLTypeResolver.class)))
            .map(ann -> resolveType(env, ann));
    if (resolvedType.isPresent()) {
        return resolvedType.get();
    }

    //Try to deduce the type
    if (returnType != null) {
        AnnotatedType resolvedJavaType = GenericTypeReflector.getExactSubType(returnType, resultType);
        if (resolvedJavaType != null && !ClassUtils.isMissingTypeParameters(resolvedJavaType.getType())) {
            GraphQLType resolved = env.getSchema().getType(typeInfoGenerator.generateTypeName(resolvedJavaType, messageBundle));
            if (resolved == null) {
                throw new UnresolvableTypeException(fieldType.getName(), result);
            }
            return (GraphQLObjectType) resolved;
        }
    }
    
    //Give up
    throw new UnresolvableTypeException(fieldType.getName(), result);
}
 
Example #21
Source File: BuildContext.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
/**
 * The shared context accessible throughout the schema generation process
 * @param basePackages The base (root) package of the entire project
 * @param environment The globally shared environment
 * @param operationRegistry Repository that can be used to fetch all known (singleton and domain) queries
 * @param typeMappers Repository of all registered {@link io.leangen.graphql.generator.mapping.TypeMapper}s
 * @param transformers Repository of all registered {@link io.leangen.graphql.generator.mapping.SchemaTransformer}s
 * @param valueMapperFactory The factory used to produce {@link ValueMapper} instances
 * @param typeInfoGenerator Generates type name/description
 * @param messageBundle The global translation message bundle
 * @param interfaceStrategy The strategy deciding what Java type gets mapped to a GraphQL interface
 * @param scalarStrategy The strategy deciding how abstract Java types are discovered
 * @param abstractInputHandler The strategy deciding what Java type gets mapped to a GraphQL interface
 * @param inputFieldBuilders The strategy deciding how GraphQL input fields are discovered from Java types
 * @param interceptorFactory The factory to use to obtain interceptors applicable to a resolver
 * @param directiveBuilder The factory used to create directives where applicable
 * @param relayMappingConfig Relay specific configuration
 * @param knownTypes The cache of known type names
 */
public BuildContext(String[] basePackages, GlobalEnvironment environment, OperationRegistry operationRegistry,
                    TypeMapperRegistry typeMappers, SchemaTransformerRegistry transformers, ValueMapperFactory valueMapperFactory,
                    TypeInfoGenerator typeInfoGenerator, MessageBundle messageBundle, InterfaceMappingStrategy interfaceStrategy,
                    ScalarDeserializationStrategy scalarStrategy, TypeTransformer typeTransformer, AbstractInputHandler abstractInputHandler,
                    InputFieldBuilderRegistry inputFieldBuilders, ResolverInterceptorFactory interceptorFactory,
                    DirectiveBuilder directiveBuilder, InclusionStrategy inclusionStrategy, RelayMappingConfig relayMappingConfig,
                    Collection<GraphQLNamedType> knownTypes, List<AnnotatedType> additionalDirectives, Comparator<AnnotatedType> typeComparator,
                    ImplementationDiscoveryStrategy implementationStrategy, GraphQLCodeRegistry.Builder codeRegistry) {
    this.operationRegistry = operationRegistry;
    this.typeRegistry = environment.typeRegistry;
    this.transformers = transformers;
    this.interceptorFactory = interceptorFactory;
    this.directiveBuilder = directiveBuilder;
    this.typeCache = new TypeCache(knownTypes);
    this.additionalDirectives = additionalDirectives;
    this.typeMappers = typeMappers;
    this.typeInfoGenerator = typeInfoGenerator;
    this.messageBundle = messageBundle;
    this.relay = environment.relay;
    this.node = knownTypes.stream()
            .filter(GraphQLUtils::isRelayNodeInterface)
            .findFirst().map(type -> (GraphQLInterfaceType) type)
            .orElse(relay.nodeInterface(new RelayNodeTypeResolver(this.typeRegistry, typeInfoGenerator, messageBundle)));
    this.typeResolver = new DelegatingTypeResolver(this.typeRegistry, typeInfoGenerator, messageBundle);
    this.interfaceStrategy = interfaceStrategy;
    this.basePackages = basePackages;
    this.valueMapperFactory = valueMapperFactory;
    this.inputFieldBuilders = inputFieldBuilders;
    this.inclusionStrategy = inclusionStrategy;
    this.scalarStrategy = scalarStrategy;
    this.typeTransformer = typeTransformer;
    this.implDiscoveryStrategy = implementationStrategy;
    this.abstractInputHandler = abstractInputHandler;
    this.globalEnvironment = environment;
    this.relayMappingConfig = relayMappingConfig;
    this.classFinder = new ClassFinder();
    this.validator = new Validator(environment, typeMappers, knownTypes, typeComparator);
    this.codeRegistry = codeRegistry;
    this.postBuildHooks = new ArrayList<>(Collections.singletonList(context -> classFinder.close()));
}
 
Example #22
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 #23
Source File: TypeCache.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
TypeCache(Collection<GraphQLNamedType> knownTypes) {
    this.knownTypes = knownTypes.stream().collect(Collectors.toMap(GraphQLNamedType::getName, Function.identity()));
}
 
Example #24
Source File: SchemaToProto.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
private static String getJspb(GraphQLNamedType type) {
  return String.format("option (jspb.message_id) = \"graphql.%s\";", type.getName());
}
 
Example #25
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 #26
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 4 votes vote down vote up
private boolean isIntrospectionType(GraphQLNamedType type) {
    return !options.isIncludeIntrospectionTypes() && type.getName().startsWith("__");
}
 
Example #27
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 4 votes vote down vote up
public Predicate<GraphQLNamedType> getIncludeTypeDefinition() {
    return includeTypeDefinition;
}
 
Example #28
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 2 votes vote down vote up
/**
 * Filter printing of type definitions. In Apollo Federation, some type definitions need to
 * be hidden, and this predicate allows filtering out such definitions. Prints all
 * definitions by default.
 *
 * @param includeTypeDefinition returns true if the definition should be printed
 * @return new instance of options
 */
public Options includeTypeDefinitions(Predicate<GraphQLNamedType> includeTypeDefinition) {
    return new Options(this.includeIntrospectionTypes, this.includeScalars, this.includeExtendedScalars, this.includeSchemaDefinition, this.useAstDefinitions, this.descriptionsAsHashComments, this.includeDirective, this.includeDirectiveDefinition, includeTypeDefinition, this.comparatorRegistry);
}