graphql.schema.GraphQLCodeRegistry Java Examples

The following examples show how to use graphql.schema.GraphQLCodeRegistry. 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: TypeRegistryTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private void assertSameType(GraphQLType t1, GraphQLType t2, GraphQLCodeRegistry code1, GraphQLCodeRegistry code2) {
    assertSame(t1, t2);
    if (t1 instanceof GraphQLInterfaceType) {
        GraphQLInterfaceType i = (GraphQLInterfaceType) t1;
        assertSame(code1.getTypeResolver(i), code2.getTypeResolver(i));
    }
    if (t1 instanceof GraphQLUnionType) {
        GraphQLUnionType u = (GraphQLUnionType) t1;
        assertSame(code1.getTypeResolver(u), code2.getTypeResolver(u));
    }
    if (t1 instanceof GraphQLFieldsContainer) {
        GraphQLFieldsContainer c = (GraphQLFieldsContainer) t1;
        c.getFieldDefinitions().forEach(fieldDef ->
                assertSame(code1.getDataFetcher(c, fieldDef), code2.getDataFetcher(c, fieldDef)));
    }
}
 
Example #2
Source File: Glitr.java    From glitr with MIT License 6 votes vote down vote up
public Glitr(TypeRegistry typeRegistry,
             GraphQLCodeRegistry.Builder codeRegistryBuilder,
             Class queryRoot,
             @Nullable GraphqlFieldVisibility fieldVisibility,
             @Nullable ObjectMapper objectMapper,
             @Nullable RelayHelper relayHelper,
             @Nullable Class mutationRoot,
             @Nullable Class subscriptionRoot,
             @Nullable QueryComplexityCalculator queryComplexityCalculator) {
    this.codeRegistryBuilder = assertNotNull(codeRegistryBuilder, "codeRegistryBuilder can't be null");
    this.typeRegistry = assertNotNull(typeRegistry, "TypeRegistry can't be null");
    assertNotNull(queryRoot, "queryRoot class can't be null");
    this.relayHelper = relayHelper;

    Glitr.objectMapper = objectMapper;
    this.schema = buildSchema(queryRoot, mutationRoot, subscriptionRoot, fieldVisibility);

    if (nonNull(queryComplexityCalculator)) {
        this.queryComplexityCalculator = queryComplexityCalculator.withSchema(this.schema);
    }
}
 
Example #3
Source File: Glitr.java    From glitr with MIT License 5 votes vote down vote up
public Glitr(TypeRegistry typeRegistry,
             GraphQLCodeRegistry.Builder codeRegistryBuilder,
             Class queryRoot,
             @Nullable GraphqlFieldVisibility fieldVisibility,
             @Nullable ObjectMapper objectMapper,
             @Nullable Class mutationRoot,
             @Nullable Class subscriptionRoot,
             @Nullable QueryComplexityCalculator queryComplexityCalculator) {
    this(typeRegistry, codeRegistryBuilder, queryRoot, fieldVisibility, objectMapper, null, mutationRoot, subscriptionRoot, queryComplexityCalculator);
}
 
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: 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 #6
Source File: GraphQLSchemaGenerator.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public GraphQLSchemaGenerator withAdditionalTypes(Collection<? extends GraphQLType> additionalTypes, GraphQLCodeRegistry codeRegistry) {
    return withAdditionalTypes(additionalTypes, new CodeRegistryMerger(codeRegistry));
}
 
Example #7
Source File: GraphQLSchemaGenerator.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
public CodeRegistryMerger(GraphQLCodeRegistry codeRegistry) {
    this.codeRegistry = codeRegistry;
}
 
Example #8
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 #9
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);