graphql.schema.idl.TypeDefinitionRegistry Java Examples

The following examples show how to use graphql.schema.idl.TypeDefinitionRegistry. 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: HGQLConfig.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
private HGQLConfig(final InputStream inputStream) {

        ObjectMapper mapper = new ObjectMapper();

        try {
            HGQLConfig config = mapper.readValue(inputStream, HGQLConfig.class);

            SchemaParser schemaParser = new SchemaParser();
            TypeDefinitionRegistry registry = schemaParser.parse(new File(config.schemaFile));

            this.name = config.name;
            this.schemaFile = config.schemaFile;
            this.graphqlConfig = config.graphqlConfig;
            checkServicePorts(config.serviceConfigs);
            this.serviceConfigs = config.serviceConfigs;
            HGQLSchemaWiring wiring = new HGQLSchemaWiring(registry, name, serviceConfigs);
            this.schema = wiring.getSchema();
            this.hgqlSchema = wiring.getHgqlSchema();
        } catch (IOException e) {
            throw new HGQLConfigurationException("Error reading from configuration file", e);
        }
    }
 
Example #2
Source File: ApolloWSHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("counter.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("staticCounter", this::getStaticCounter))
    .type("Subscription", builder -> builder.dataFetcher("counter", this::getCounter))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example #3
Source File: LocaleTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("locale.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("locale", this::getLocale))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example #4
Source File: FederationTest.java    From federation-jvm with MIT License 6 votes vote down vote up
@Test
void testPrinterEmpty() {
    TypeDefinitionRegistry typeDefinitionRegistry = new SchemaParser().parse(printerEmptySDL);
    RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
            .type("Interface1", typeWiring -> typeWiring
                    .typeResolver(env -> null)
            )
            .type("Interface2", typeWiring -> typeWiring
                    .typeResolver(env -> null)
            )
            .build();
    GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(
            typeDefinitionRegistry,
            runtimeWiring
    );
    Assertions.assertEquals(
            printerEmptySDL.trim(),
            new FederationSdlPrinter(FederationSdlPrinter.Options.defaultOptions()
                    .includeDirectiveDefinitions(def -> !standardDirectives.contains(def.getName()))
            ).print(graphQLSchema).trim()
    );
}
 
Example #5
Source File: GraphQLTestBase.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("links.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("allLinks", this::getAllLinks))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example #6
Source File: Federation.java    From federation-jvm with MIT License 6 votes vote down vote up
private static RuntimeWiring ensureFederationDirectiveDefinitionsExist(
        TypeDefinitionRegistry typeRegistry,
        RuntimeWiring runtimeWiring
) {
    // Add Federation directives if they don't exist.
    FederationDirectives.allDefinitions
            .stream()
            .filter(def -> !typeRegistry.getDirectiveDefinition(def.getName()).isPresent())
            .forEachOrdered(typeRegistry::add);

    // Add scalar type for _FieldSet, since the directives depend on it.
    if (!typeRegistry.getType(_FieldSet.typeName).isPresent()) {
        typeRegistry.add(_FieldSet.definition);
    }

    // Also add the implementation for _FieldSet.
    if (!runtimeWiring.getScalars().containsKey(_FieldSet.typeName)) {
        return copyRuntimeWiring(runtimeWiring).scalar(_FieldSet.type).build();
    } else {
        return runtimeWiring;
    }
}
 
Example #7
Source File: VertxMappedBatchLoaderTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("links.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("allLinks", this::getAllLinks))
    .type("Link", builder -> builder.dataFetcher("postedBy", this::getLinkPostedBy))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
  DataLoaderDispatcherInstrumentation dispatcherInstrumentation = new DataLoaderDispatcherInstrumentation();

  return GraphQL.newGraphQL(graphQLSchema)
    .instrumentation(dispatcherInstrumentation)
    .build();
}
 
Example #8
Source File: VertxDataFetcherTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("links.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> {
      VertxDataFetcher<Object> dataFetcher = VertxDataFetcher.create((env, fut) -> fut.complete(getAllLinks(env)));
      return builder.dataFetcher("allLinks", dataFetcher);
    })
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example #9
Source File: VertxBatchLoaderTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQL graphQL() {
  String schema = vertx.fileSystem().readFileBlocking("links.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("allLinks", this::getAllLinks))
    .type("Link", builder -> builder.dataFetcher("postedBy", this::getLinkPostedBy))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
  DataLoaderDispatcherInstrumentation dispatcherInstrumentation = new DataLoaderDispatcherInstrumentation();

  return GraphQL.newGraphQL(graphQLSchema)
    .instrumentation(dispatcherInstrumentation)
    .build();
}
 
Example #10
Source File: ApolloTestsServer.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private GraphQL setupGraphQL() {
  String schema = vertx.fileSystem().readFileBlocking("links.graphqls").toString();
  String uploadSchema = vertx.fileSystem().readFileBlocking("upload.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema)
    .merge(schemaParser.parse(uploadSchema));

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .scalar(UploadScalar.build())
    .type("Query", builder -> builder.dataFetcher("allLinks", this::getAllLinks))
    .type("Mutation", builder -> builder.dataFetcher("singleUpload", this::singleUpload))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example #11
Source File: ApolloTestsServer.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private GraphQL setupWsGraphQL() {
  String schema = vertx.fileSystem().readFileBlocking("counter.graphqls").toString();

  SchemaParser schemaParser = new SchemaParser();
  TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

  RuntimeWiring runtimeWiring = newRuntimeWiring()
    .type("Query", builder -> builder.dataFetcher("staticCounter", this::staticCounter))
    .type("Subscription", builder -> builder.dataFetcher("counter", this::counter))
    .build();

  SchemaGenerator schemaGenerator = new SchemaGenerator();
  GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema)
    .build();
}
 
Example #12
Source File: MultipartRequestTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private GraphQL graphQL() {
  final String schema = vertx.fileSystem().readFileBlocking("upload.graphqls").toString();
  final String emptyQueryschema = vertx.fileSystem().readFileBlocking("emptyQuery.graphqls").toString();

  final SchemaParser schemaParser = new SchemaParser();
  final TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema)
    .merge(schemaParser.parse(emptyQueryschema));

  final RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
    .scalar(UploadScalar.build())
    .type("Mutation", builder -> {
      builder.dataFetcher("singleUpload", this::singleUpload);
      builder.dataFetcher("multipleUpload", this::multipleUpload);
      return builder;
    }).build();

  final SchemaGenerator schemaGenerator = new SchemaGenerator();
  final GraphQLSchema graphQLSchema = schemaGenerator
    .makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

  return GraphQL.newGraphQL(graphQLSchema).build();
}
 
Example #13
Source File: GraphQLSchemaDefinition.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Extract GraphQL Operations from given schema
 * @param schema graphQL Schema
 * @return the arrayList of APIOperationsDTOextractGraphQLOperationList
 *
 */
public List<URITemplate> extractGraphQLOperationList(String schema, String type) {
    List<URITemplate> operationArray = new ArrayList<>();
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
    Map<java.lang.String, TypeDefinition> operationList = typeRegistry.types();
    for (Map.Entry<String, TypeDefinition> entry : operationList.entrySet()) {
        if (entry.getValue().getName().equals(APIConstants.GRAPHQL_QUERY) ||
                entry.getValue().getName().equals(APIConstants.GRAPHQL_MUTATION)
                || entry.getValue().getName().equals(APIConstants.GRAPHQL_SUBSCRIPTION)) {
            if (type == null) {
                addOperations(entry, operationArray);
            } else if (type.equals(entry.getValue().getName().toUpperCase())) {
                addOperations(entry, operationArray);
            }
        }
    }
    return operationArray;
}
 
Example #14
Source File: HGQLConfigService.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
HGQLConfig loadHGQLConfig(final String hgqlConfigPath, final InputStream inputStream, final String username, final String password, boolean classpath) {

        final ObjectMapper mapper = new ObjectMapper();

        try {

            final HGQLConfig config = mapper.readValue(inputStream, HGQLConfig.class);
            final SchemaParser schemaParser = new SchemaParser();

            final String fullSchemaPath = extractFullSchemaPath(hgqlConfigPath, config.getSchemaFile());

            LOGGER.debug("Schema config path: " + fullSchemaPath);

            final Reader reader = selectAppropriateReader(fullSchemaPath, username, password, classpath);
            final TypeDefinitionRegistry registry =
                    schemaParser.parse(reader);

            final HGQLSchemaWiring wiring = new HGQLSchemaWiring(registry, config.getName(), config.getServiceConfigs());
            config.setGraphQLSchema(wiring.getSchema());
            config.setHgqlSchema(wiring.getHgqlSchema());
            return config;

        } catch (IOException | URISyntaxException e) {
            throw new HGQLConfigurationException("Error reading from configuration file", e);
        }
    }
 
Example #15
Source File: GraphQLCompletionContributor.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
private void completeImplementsTypeName() {
    CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
            final PsiElement completionElement = parameters.getPosition();
            final GraphQLImplementsInterfaces implementsInterfaces = PsiTreeUtil.getParentOfType(completionElement, GraphQLImplementsInterfaces.class);
            if (implementsInterfaces != null) {
                final Set<String> currentInterfaces = Sets.newHashSet();
                implementsInterfaces.getTypeNameList().forEach(t -> currentInterfaces.add(t.getName()));
                final TypeDefinitionRegistry typeDefinitionRegistry = GraphQLTypeDefinitionRegistryServiceImpl.getService(completionElement.getProject()).getRegistry(parameters.getOriginalFile());
                typeDefinitionRegistry.getTypes(InterfaceTypeDefinition.class).forEach(schemaInterface -> {
                    if (currentInterfaces.add(schemaInterface.getName())) {
                        result.addElement(LookupElementBuilder.create(schemaInterface.getName()));
                    }
                });
            }
        }
    };
    extend(CompletionType.BASIC, psiElement(GraphQLElementTypes.NAME).inside(psiElement(GraphQLElementTypes.TYPE_NAME).inside(psiElement(GraphQLElementTypes.IMPLEMENTS_INTERFACES))), provider);
}
 
Example #16
Source File: GraphQLFactory.java    From micronaut-graphql with Apache License 2.0 6 votes vote down vote up
@Bean
@Singleton
public GraphQL graphQL(ResourceResolver resourceResolver, HelloDataFetcher helloDataFetcher) { // <2>

    SchemaParser schemaParser = new SchemaParser();
    SchemaGenerator schemaGenerator = new SchemaGenerator();

    // Parse the schema.
    TypeDefinitionRegistry typeRegistry = new TypeDefinitionRegistry();
    typeRegistry.merge(schemaParser.parse(new BufferedReader(new InputStreamReader(
            resourceResolver.getResourceAsStream("classpath:schema.graphqls").get()))));

    // Create the runtime wiring.
    RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
            .type("Query", typeWiring -> typeWiring
                    .dataFetcher("hello", helloDataFetcher))
            .build();

    // Create the executable schema.
    GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);

    // Return the GraphQL bean.
    return GraphQL.newGraphQL(graphQLSchema).build();
}
 
Example #17
Source File: GraphQLCompletionContributor.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
private void completeFieldArgumentTypeName() {
    CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {

            final PsiElement completionElement = parameters.getPosition();
            final TypeDefinitionRegistry registry = GraphQLTypeDefinitionRegistryServiceImpl.getService(completionElement.getProject()).getRegistry(parameters.getOriginalFile());
            addInputTypeCompletions(result, registry);
        }
    };
    extend(CompletionType.BASIC,
            psiElement(GraphQLElementTypes.NAME).afterLeafSkipping(
                    // skip
                    PlatformPatterns.or(psiComment(), psiElement(TokenType.WHITE_SPACE), psiElement().withText("[")),
                    // until argument type colon occurs
                    psiElement().withText(":")
            ).inside(GraphQLInputValueDefinition.class), provider);
}
 
Example #18
Source File: GraphQLCompletionContributor.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
private void completeOperationTypeNamesInSchemaDefinition() {
    CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
            final PsiElement completionElement = parameters.getPosition();
            final TypeDefinitionRegistry registry = GraphQLTypeDefinitionRegistryServiceImpl.getService(completionElement.getProject()).getRegistry(parameters.getOriginalFile());
            if (registry != null) {
                final Collection<GraphQLTypeName> currentTypes = PsiTreeUtil.findChildrenOfType(PsiTreeUtil.getTopmostParentOfType(completionElement, GraphQLElement.class), GraphQLTypeName.class);
                final Set<String> currentTypeNames = currentTypes.stream().map(PsiNamedElement::getName).collect(Collectors.toSet());
                registry.types().values().forEach(type -> {
                    if (type instanceof ObjectTypeDefinition && !currentTypeNames.contains(type.getName())) {
                        result.addElement(LookupElementBuilder.create(type.getName()));
                    }
                });
            }
        }
    };
    extend(CompletionType.BASIC, psiElement(GraphQLElementTypes.NAME).afterLeaf(":").inside(GraphQLOperationTypeDefinition.class), provider);
}
 
Example #19
Source File: ApiDesignResourceInfo.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
private static ApiDesignResourceInfo fromGraphQLContent(String content) {
    try {
        SchemaParser schemaParser = new SchemaParser();
        TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(content);
        int numTypes = typeDefinitionRegistry.types().size();
        ApiDesignResourceInfo info = new ApiDesignResourceInfo();
        info.setFormat(FormatType.SDL);
        info.setName("Imported GraphQL Schema");
        String typeList = String.join(", ", typeDefinitionRegistry.types().keySet());
        info.setDescription("An imported GraphQL schema with the following " + numTypes + " types: " + typeList);
        info.setType(ApiDesignType.GraphQL);
        return info;
    } catch (Exception e) {
    }
    return null;
}
 
Example #20
Source File: GraphQLFactory.java    From dropwizard-graphql with Apache License 2.0 6 votes vote down vote up
public GraphQLSchema build() throws SchemaProblem {
  if (graphQLSchema.isPresent()) {
    return graphQLSchema.get();
  }

  final SchemaParser parser = new SchemaParser();
  final TypeDefinitionRegistry registry = new TypeDefinitionRegistry();

  if (!schemaFiles.isEmpty()) {
    schemaFiles.stream()
        .filter(f -> !Strings.isNullOrEmpty(f))
        .map(f -> getResourceAsReader(f))
        .map(r -> parser.parse(r))
        .forEach(p -> registry.merge(p));
  }

  final SchemaGenerator generator = new SchemaGenerator();
  final GraphQLSchema schema = generator.makeExecutableSchema(registry, runtimeWiring);
  return schema;
}
 
Example #21
Source File: GraphQLSchemaDefinition.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Extract GraphQL Types and Fields from given schema
 *
 * @param schema GraphQL Schema
 * @return list of all types and fields
 */
public List<GraphqlSchemaType> extractGraphQLTypeList(String schema) {
    List<GraphqlSchemaType> typeList = new ArrayList<>();
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
    Map<java.lang.String, TypeDefinition> list = typeRegistry.types();
    for (Map.Entry<String, TypeDefinition> entry : list.entrySet()) {
        if (entry.getValue() instanceof ObjectTypeDefinition) {
            GraphqlSchemaType graphqlSchemaType = new GraphqlSchemaType();
            List<String> fieldList = new ArrayList<>();
            graphqlSchemaType.setType(entry.getValue().getName());
            for (FieldDefinition fieldDef : ((ObjectTypeDefinition) entry.getValue()).getFieldDefinitions()) {
                fieldList.add(fieldDef.getName());
            }
            graphqlSchemaType.setFieldList(fieldList);
            typeList.add(graphqlSchemaType);
        }
    }
    return typeList;
}
 
Example #22
Source File: VertxGraphqlResource.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public void setupRouter(@Observes Router router) {
    String schema = "type Query{hello: String}";

    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);

    RuntimeWiring runtimeWiring = RuntimeWiring.newRuntimeWiring()
            .type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
            .build();

    SchemaGenerator schemaGenerator = new SchemaGenerator();
    GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);

    GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build();

    router.route("/graphql").handler(ApolloWSHandler.create(graphQL));
    router.route("/graphql").handler(GraphQLHandler.create(graphQL));
}
 
Example #23
Source File: GraphQLIntegrationTest.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
private static GraphQLSchema getGraphQLSchema() throws Exception {
  SchemaParser schemaParser = new SchemaParser();
  SchemaGenerator schemaGenerator = new SchemaGenerator();

  URL resource = Thread.currentThread().getContextClassLoader().getResource("schema.graphqls");
  Path path = Paths.get(resource.toURI());
  String s = read(path);

  TypeDefinitionRegistry registry = schemaParser.parse(s);

  RuntimeWiring wiring =
      RuntimeWiring.newRuntimeWiring()
          .type(
              newTypeWiring("Query")
                  .dataFetcher("bookById", GraphQLDataFetchers.getBookByIdDataFetcher()))
          .type(
              newTypeWiring("Book")
                  .dataFetcher("author", GraphQLDataFetchers.getAuthorDataFetcher()))
          .build();

  return schemaGenerator.makeExecutableSchema(registry, wiring);
}
 
Example #24
Source File: GraphQLCompletionContributor.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
/**
 * Gets whether the specified fragment candidate is valid to spread inside the specified required type scope
 *
 * @param typeDefinitionRegistry registry with available schema types, used to resolve union members and interface implementations
 * @param fragmentCandidate      the fragment to check for being able to validly spread under the required type scope
 * @param requiredTypeScope      the type scope in which the fragment is a candidate to spread
 * @return true if the fragment candidate is valid to be spread inside the type scope
 */
private boolean isFragmentApplicableInTypeScope(TypeDefinitionRegistry typeDefinitionRegistry, GraphQLFragmentDefinition fragmentCandidate, GraphQLType requiredTypeScope) {

    // unwrap non-nullable and list types
    requiredTypeScope = GraphQLUtil.getUnmodifiedType(requiredTypeScope);

    final GraphQLTypeCondition typeCondition = fragmentCandidate.getTypeCondition();
    if (typeCondition == null || typeCondition.getTypeName() == null) {
        return false;
    }

    final String fragmentTypeName = Optional.ofNullable(typeCondition.getTypeName().getName()).orElse("");
    if (fragmentTypeName.equals(GraphQLUtil.getName(requiredTypeScope))) {
        // direct match, e.g. User scope, fragment on User
        return true;
    }

    // check whether compatible based on interfaces and unions
    return isCompatibleFragment(typeDefinitionRegistry, requiredTypeScope, fragmentTypeName);

}
 
Example #25
Source File: GqlParentType.java    From manifold with Apache License 2.0 5 votes vote down vote up
GqlParentType( String fqn, SchemaDefinition schemaDefinition, TypeDefinitionRegistry registry,
               Map<String, OperationDefinition> operations, Map<String, FragmentDefinition> fragments,
               IFile file, GqlManifold gqlManifold )
{
  _fqn = fqn;
  _schemaDefinition = schemaDefinition;
  _registry = registry;
  _operations = operations;
  _fragments = fragments;
  _file = file;
  _gqlManifold = gqlManifold;
  _typeToUnions = new HashMap<>();
}
 
Example #26
Source File: JSGraphQLEndpointNamedTypeRegistry.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
public TypeDefinitionRegistryWithErrors getTypesAsRegistry(PsiElement scopedElement) {
    final GraphQLNamedScope schemaScope = getSchemaScope(scopedElement);
    if (schemaScope == null) {
        return new TypeDefinitionRegistryWithErrors(new TypeDefinitionRegistry(), Collections.emptyList(), false);
    }
    return projectToRegistry.computeIfAbsent(schemaScope, p -> doGetTypesAsRegistry(scopedElement));
}
 
Example #27
Source File: GraphqlHandler.java    From selenium with Apache License 2.0 5 votes vote down vote up
private TypeDefinitionRegistry buildTypeDefinitionRegistry() {
  try (InputStream stream = getClass().getResourceAsStream(GRID_SCHEMA)) {
    return new SchemaParser().parse(stream);
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example #28
Source File: HGQLSchemaWiringTest.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Constructor exception with null for last parameter")
void should_throw_exception_on_construction_from_last_null() {

    TypeDefinitionRegistry registry = mock(TypeDefinitionRegistry.class);
    Executable executable = () -> new HGQLSchemaWiring(registry, "local", null);
    Throwable exception = assertThrows(HGQLConfigurationException.class, executable);
    assertEquals("Unable to perform schema wiring", exception.getMessage());
}
 
Example #29
Source File: BarleyGraphQLSchema.java    From barleydb with GNU Lesser General Public License v3.0 5 votes vote down vote up
public BarleyGraphQLSchema(SpecRegistry specRegistry, Environment env, String namespace, CustomQueries customQueries) {
	this.specRegistry = specRegistry;
	this.env = env;
	this.namespace = namespace;
	this.queryCustomizations = new GraphQLQueryCustomizations();
	this.queryCustomizations.setShouldBreakPredicate(new DefaultQueryBreaker(env, namespace, 3, 4));

       GenerateGrapqlSDL graphSdl = new GenerateGrapqlSDL(specRegistry, customQueries);
       
       SchemaParser schemaParser = new SchemaParser();
       sdlString = graphSdl.createSdl();
       LOG.info(sdlString);
       System.out.println(sdlString);
       
       TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(sdlString);
       RuntimeWiring.Builder wiringBuilder = newRuntimeWiring()
               .type("Query", builder -> builder.defaultDataFetcher(new QueryDataFetcher(env, namespace, customQueries)));
       
       specRegistry.getDefinitions().stream()
       .map(DefinitionsSpec::getEntitySpecs)
       .flatMap(Collection::stream)
       .forEach(eSpec -> wiringBuilder.type(getSimpleName(eSpec.getClassName()), builder ->  builder.defaultDataFetcher(new EntityDataFetcher(env, namespace))));
       
        RuntimeWiring runtimeWiring = wiringBuilder.build();        
       
       SchemaGenerator schemaGenerator = new SchemaGenerator();
       this.graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
}
 
Example #30
Source File: GqlModel.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void buildRegistry( Document document )
{
  TypeDefinitionRegistry typeRegistry = new TypeDefinitionRegistry();
  List<Definition> definitions = document.getDefinitions();
  Map<String, OperationDefinition> operations = new LinkedHashMap<>();
  Map<String, FragmentDefinition> fragments = new LinkedHashMap<>();
  List<GraphQLError> errors = new ArrayList<>();
  for( Definition definition: definitions )
  {
    if( definition instanceof SchemaDefinition )
    {
      _schemaDefinition = (SchemaDefinition)definition;
    }
    else if( definition instanceof SDLDefinition )
    {
      // types, interfaces, unions, inputs, scalars, extensions
      typeRegistry.add( (SDLDefinition)definition ).ifPresent( errors::add );
      if( definition instanceof ScalarTypeDefinition )
      {
        // register scalar type
        typeRegistry.scalars().put( ((ScalarTypeDefinition)definition).getName(), (ScalarTypeDefinition)definition );
      }
    }
    else if( definition instanceof OperationDefinition )
    {
      // queries, mutations, subscriptions
      operations.put( ((OperationDefinition)definition).getName(), (OperationDefinition)definition );
    }
    else if( definition instanceof FragmentDefinition )
    {
      // fragments
      fragments.put( ((FragmentDefinition)definition).getName(), (FragmentDefinition)definition );
    }
  }
  _issues = new GqlIssueContainer( errors, getFile() );
  _typeRegistry = typeRegistry;
  _operations = operations;
  _fragments = fragments;
}