graphql.schema.GraphQLSchema Java Examples

The following examples show how to use graphql.schema.GraphQLSchema. 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: GenerateSchemaMojo.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private String generateSchema(IndexView index) {
    Config config = new Config() {
        @Override
        public boolean isIncludeScalarsInSchema() {
            return includeScalars;
        }

        @Override
        public boolean isIncludeDirectivesInSchema() {
            return includeDirectives;
        }

        @Override
        public boolean isIncludeSchemaDefinitionInSchema() {
            return includeSchemaDefinition;
        }

        @Override
        public boolean isIncludeIntrospectionTypesInSchema() {
            return includeIntrospectionTypes;
        }
    };
    Schema internalSchema = SchemaBuilder.build(index);
    GraphQLSchema graphQLSchema = Bootstrap.bootstrap(internalSchema);
    return new SchemaPrinter(config).print(graphQLSchema);
}
 
Example #2
Source File: TypeResolverTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
    public void testTypeResolver() {
        GraphQLSchema schema = new TestSchemaGenerator()
                .withOperationsFromSingleton(new RepoService())
                .generate();

        GraphQL exe = GraphQL.newGraphQL(schema).build();
        String queryTemplate = "{repo(id: %d) {" +
                "identifier,  " +
                "... on SessionRepo_Street {street: item {name}} " +
                "... on SessionRepo_Education {school: item {schoolName}}}}";
        ExecutionResult result = exe.execute(String.format(queryTemplate, 2));
        assertNoErrors(result);
        assertValueAtPathEquals("Baker street", result, "repo.0.0.street.name");
//        exe.execute("{repo(id: 3) {key {identifier  ... on SessionRepo_Street {street: item {name}} ... on SessionRepo_Education {school: item {schoolName}}}}}}", new HashMap<>());
//        result = exe.execute("{repo(id: 3) {identifier  ... on SessionRepo_Street {street: item {name}} }}");
        result = exe.execute(String.format(queryTemplate, 3));
        assertNoErrors(result);
        assertValueAtPathEquals("Alma Mater", result, "repo.0.0.school.schoolName");
    }
 
Example #3
Source File: GraphqlHandler.java    From selenium with Apache License 2.0 6 votes vote down vote up
public GraphqlHandler(Distributor distributor, URI publicUri) {
  this.distributor = Objects.requireNonNull(distributor);
  this.publicUri = Objects.requireNonNull(publicUri);

  GraphQLSchema schema = new SchemaGenerator()
    .makeExecutableSchema(buildTypeDefinitionRegistry(), buildRuntimeWiring());

  Cache<String, PreparsedDocumentEntry> cache = CacheBuilder.newBuilder()
    .maximumSize(1024)
    .build();

  graphQl = GraphQL.newGraphQL(schema)
    .preparsedDocumentProvider((executionInput, computeFunction) -> {
      try {
        return cache.get(executionInput.getQuery(), () -> computeFunction.apply(executionInput));
      } catch (ExecutionException e) {
        if (e.getCause() instanceof RuntimeException) {
          throw (RuntimeException) e.getCause();
        } else if (e.getCause() != null) {
          throw new RuntimeException(e.getCause());
        }
        throw new RuntimeException(e);
      }
    })
    .build();
}
 
Example #4
Source File: RelayTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
public void testRelayMutations() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new UserService<Education>(), new TypeToken<UserService<Education>>(){}.getAnnotatedType())
            .withTypeAdapters(new MapToListTypeAdapter())
            .withRelayCompliantMutations()
            .generate();

    GraphQL exe = GraphQL.newGraphQL(schema).build();

    //Check with the default context
    ExecutionResult result = exe.execute(ExecutionInput.newExecutionInput()
            .query(relayMapInputMutation)
            .context(GraphQLContext.newContext().build()) //Needed because of a bug in graphql-java v12
            .build());
    assertNoErrors(result);
    assertValueAtPathEquals("123", result, "upMe." + GraphQLUtils.CLIENT_MUTATION_ID);

    //Check with the wrapped context
    exe = GraphQLRuntime.newGraphQL(schema).build();
    result = exe.execute(relayMapInputMutation);
    assertNoErrors(result);
    assertValueAtPathEquals("123", result, "upMe." + GraphQLUtils.CLIENT_MUTATION_ID);
}
 
Example #5
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 #6
Source File: PrimitivesTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
public void nonNullBooleanVoidTest() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new BooleanVoidService())
            .generate();
    GraphQLObjectType query = schema.getQueryType();
    GraphQLFieldDefinition field;

    field = query.getFieldDefinition("primitiveVoid");
    assertNonNull(field.getType(), Scalars.GraphQLBoolean);

    field = query.getFieldDefinition("objVoid");
    assertSame(field.getType(), Scalars.GraphQLBoolean);

    field = query.getFieldDefinition("primitiveBoolean");
    assertNonNull(field.getType(), Scalars.GraphQLBoolean);
    assertNonNull(field.getArgument("in").getType(), Scalars.GraphQLBoolean);

    field = query.getFieldDefinition("objBoolean");
    assertSame(field.getType(), Scalars.GraphQLBoolean);
    assertSame(field.getArgument("in").getType(), Scalars.GraphQLBoolean);
}
 
Example #7
Source File: SchemaToProto.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("JdkObsolete")
static Set<GraphQLType> getAllTypes(GraphQLSchema schema) {
  LinkedHashSet<GraphQLType> types = new LinkedHashSet<>();
  LinkedList<GraphQLObjectType> loop = new LinkedList<>();
  loop.add(schema.getQueryType());
  types.add(schema.getQueryType());

  while (!loop.isEmpty()) {
    for (GraphQLFieldDefinition field : loop.pop().getFieldDefinitions()) {
      GraphQLType type = field.getType();
      if (type instanceof GraphQLList) {
        type = ((GraphQLList) type).getWrappedType();
      }
      if (!types.contains(type)) {
        if (type instanceof GraphQLEnumType) {
          types.add(field.getType());
        }
        if (type instanceof GraphQLObjectType) {
          types.add(type);
          loop.add((GraphQLObjectType) type);
        }
      }
    }
  }
  return types;
}
 
Example #8
Source File: JsonResultsTest.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()
    .wiringFactory(new WiringFactory() {
      @Override
      public DataFetcher getDefaultDataFetcher(FieldWiringEnvironment environment) {
        return VertxPropertyDataFetcher.create(environment.getFieldDefinition().getName());
      }
    })
    .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 #9
Source File: TypeRegistryTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
public void additionalTypesFullCopyTest() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new Service())
            .generate();

    GraphQLSchema schema2 = new TestSchemaGenerator()
            .withOperationsFromSingleton(new Service())
            .withAdditionalTypes(schema.getAllTypesAsList(), schema.getCodeRegistry())
            .generate();

    schema.getTypeMap().values().stream()
            .filter(type -> !GraphQLUtils.isIntrospectionType(type) && type != schema.getQueryType())
            .forEach(type -> {
                assertTrue(schema2.getTypeMap().containsKey(type.getName()));
                GraphQLType type2 = schema2.getTypeMap().get(type.getName());
                assertSameType(type, type2, schema.getCodeRegistry(), schema2.getCodeRegistry());
            });

    GraphQL exe = GraphQL.newGraphQL(schema2).build();
    ExecutionResult result = exe.execute("{mix(id: \"1\") {... on Street {name}}}");
    assertNoErrors(result);
}
 
Example #10
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 #11
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 #12
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 #13
Source File: PolymorphicJsonTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
public void testPolymorphicInput() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withValueMapperFactory(valueMapperFactory)
            .withAbstractInputTypeResolution()
            .withOperationsFromSingleton(new Operations())
            .generate();

    GraphQL exe = GraphQL.newGraphQL(schema).build();
    ExecutionResult result = exe.execute("{" +
            "test (container: {" +
            "       item: \"yay\"," +
            "       _type_: Child}) {" +
            "   item}}");
    assertNoErrors(result);
    assertValueAtPathEquals("yayChild", result, "test.item");
}
 
Example #14
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private void addQueries(GraphQLSchema.Builder schemaBuilder) {

        GraphQLObjectType.Builder queryBuilder = GraphQLObjectType.newObject()
                .name(QUERY)
                .description("Query root");

        if (schema.hasQueries()) {
            Set<Operation> queries = schema.getQueries();
            for (Operation queryOperation : queries) {
                GraphQLFieldDefinition graphQLFieldDefinition = createGraphQLFieldDefinitionFromOperation(QUERY,
                        queryOperation);
                queryBuilder = queryBuilder.field(graphQLFieldDefinition);
            }
        }

        GraphQLObjectType query = queryBuilder.build();
        schemaBuilder.query(query);
    }
 
Example #15
Source File: RelayTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtendedPageMapping() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new ExtendedPageBookService())
            .generate();

    GraphQLFieldDefinition totalCount = schema.getObjectType("BookConnection")
            .getFieldDefinition("totalCount");
    assertNotNull(totalCount);
    assertNonNull(totalCount.getType(), Scalars.GraphQLLong);
    GraphQL exe = GraphQLRuntime.newGraphQL(schema).build();

    ExecutionResult result = exe.execute("{extended(first:10, after:\"20\") {" +
            "   totalCount" +
            "   pageInfo {" +
            "       hasNextPage" +
            "   }," +
            "   edges {" +
            "       cursor, node {" +
            "           title" +
            "}}}}");
    assertNoErrors(result);
    assertValueAtPathEquals(100L, result, "extended.totalCount");
    assertValueAtPathEquals("Tesseract", result, "extended.edges.0.node.title");
}
 
Example #16
Source File: GenerateSchemaTask.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private String generateSchema(IndexView index) {
    Config config = new Config() {
        @Override
        public boolean isIncludeScalarsInSchema() {
            return includeScalars;
        }

        @Override
        public boolean isIncludeDirectivesInSchema() {
            return includeDirectives;
        }

        @Override
        public boolean isIncludeSchemaDefinitionInSchema() {
            return includeSchemaDefinition;
        }

        @Override
        public boolean isIncludeIntrospectionTypesInSchema() {
            return includeIntrospectionTypes;
        }
    };
    Schema internalSchema = SchemaBuilder.build(index);
    GraphQLSchema graphQLSchema = Bootstrap.bootstrap(internalSchema);
    return new SchemaPrinter(config).print(graphQLSchema);
}
 
Example #17
Source File: GraphQLTypedOperationDefinitionPsiElement.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public GraphQLType getTypeScope() {
    final GraphQLSchema schema = GraphQLTypeDefinitionRegistryServiceImpl.getService(getProject()).getSchema(this);
    if (schema != null) {
        final IElementType operationType = getOperationType().getNode().getFirstChildNode().getElementType();
        if (operationType == GraphQLElementTypes.QUERY_KEYWORD) {
            return schema.getQueryType();
        } else if (operationType == GraphQLElementTypes.MUTATION_KEYWORD) {
            return schema.getMutationType();
        } else if (operationType == GraphQLElementTypes.SUBSCRIPTION_KEYWORD) {
            return schema.getSubscriptionType();
        }
    }
    return null;
}
 
Example #18
Source File: GraphqlProvider.java    From dive-into-graphql-in-java with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
public void init() throws IOException {
    URL url = Resources.getResource("graphql/schema.graphqls");
    String sdl = Resources.toString(url, Charsets.UTF_8);
    GraphQLSchema graphQLSchema = buildSchema(sdl);
    this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
}
 
Example #19
Source File: DiveIntoGraphqlInJavaApplication.java    From dive-into-graphql-in-java with GNU General Public License v3.0 5 votes vote down vote up
private static GraphQLSchema buildSchema(SpeakerService speakerService, AttendeeService attendeeService, TalkService talkService) {
		return SchemaParser
				.newParser()
				.file("graphql/schema.graphqls")
//                .dictionary()
				.resolvers( new Query(attendeeService,speakerService,talkService),
						new TalkReslover(speakerService),
						new Mutation(speakerService))
				.build()
				.makeExecutableSchema();
	}
 
Example #20
Source File: DiveIntoGraphqlInJavaApplication.java    From dive-into-graphql-in-java with GNU General Public License v3.0 5 votes vote down vote up
private static GraphQLSchema buildSchema(SpeakerService speakerService, AttendeeService attendeeService, TalkService talkService) {
		return SchemaParser
				.newParser()
				.file("graphql/schema.graphqls")
//                .dictionary()
				.resolvers( new Query(attendeeService,speakerService,talkService),
						new TalkReslover(speakerService))
				.build()
				.makeExecutableSchema();
	}
 
Example #21
Source File: DiveIntoGraphqlInJavaApplication.java    From dive-into-graphql-in-java with GNU General Public License v3.0 5 votes vote down vote up
private static GraphQLSchema buildSchema(SpeakerService speakerService, AttendeeService attendeeService, TalkService talkService) {
		return SchemaParser
				.newParser()
				.file("graphql/schema.graphqls")
//                .dictionary()
				.resolvers( new Query(attendeeService,speakerService,talkService),
						new TalkReslover(speakerService))
				.build()
				.makeExecutableSchema();
	}
 
Example #22
Source File: TypeGeneratorTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testGraphQLInterfaces() throws JsonProcessingException {
    logger.debug("testGraphQLInterfaces");
    Object interfaceType = generator.getInterfaceType(InterfaceChild.class);
    assertThat(interfaceType, instanceOf(GraphQLInterfaceType.class));
    
    GraphQLObjectType queryType = newObject()
            .name("testQuery")
            .field(newFieldDefinition()
                    .type((GraphQLOutputType) interfaceType)
                    .name("testObj")
                    .staticValue(new InterfaceImpl())
                    .build())
            .build();
    GraphQLSchema testSchema = GraphQLSchema.newSchema()
            .query(queryType)
            .build();
    
    String queryString = 
    "{"
    + "  testObj {"
    + "    parent"
    + "    child"
    + "  }"
    + "}";
    ExecutionResult queryResult = new GraphQL(testSchema).execute(queryString);
    assertThat(queryResult.getErrors(), is(empty()));
    Map<String, Object> resultMap = (Map<String, Object>) queryResult.getData();
    if (logger.isDebugEnabled()) {
        logger.debug("testGraphQLInterfaces resultMap {}", prettyPrint(resultMap));
    }
    
    assertThat(((Map<String, Object>)resultMap.get("testObj")),
            equalTo((Map<String, Object>) new HashMap<String, Object>() {{
                put("parent", "parent");
                put("child", "child");
            }}));
    assertThat(((Map<String, Object>)resultMap.get("testObj")).size(),
            is(2));
}
 
Example #23
Source File: FieldOrderTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private static ExecutionResult introspect() {
    GraphQLSchema schema = new GraphQLSchemaGenerator()
            .withBasePackages(FieldOrderTest.class.getPackage().getName())
            .withOperationsFromSingletons(new Query())
            .generate();
    GraphQL graphQL = GraphQL.newGraphQL(schema).build();
    return graphQL.execute(IntrospectionQuery.INTROSPECTION_QUERY);
}
 
Example #24
Source File: UnionTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testAutoDiscoveredUnionInterface() {
    AutoDiscoveredUnionService unionService = new AutoDiscoveredUnionService();

    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(unionService)
            .generate();

    GraphQLUnionType union = (GraphQLUnionType) schema.getQueryType().getFieldDefinition("union").getType();
    assertUnionOf(union, schema.getType("A1"), schema.getType("A2"));
    assertEquals("Strong_union", union.getName());
    assertEquals("This union is strong!", union.getDescription());
}
 
Example #25
Source File: GraphQLProvider.java    From graphql-java-examples with MIT License 5 votes vote down vote up
@PostConstruct
public void init() throws IOException {
    URL url = Resources.getResource("schema.graphql");
    String sdl = Resources.toString(url, Charsets.UTF_8);
    GraphQLSchema graphQLSchema = buildSchema(sdl);
    this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
}
 
Example #26
Source File: GraphQLFactory.java    From micronaut-graphql with Apache License 2.0 5 votes vote down vote up
@Bean
@Singleton
public GraphQL graphQL(ToDoQueryResolver toDoQueryResolver, ToDoMutationResolver toDoMutationResolver) {

    // Parse the schema.
    SchemaParserBuilder builder = SchemaParser.newParser()
            .file("schema.graphqls")
            .resolvers(toDoQueryResolver, toDoMutationResolver);

    // Create the executable schema.
    GraphQLSchema graphQLSchema = builder.build().makeExecutableSchema();

    // Return the GraphQL bean.
    return GraphQL.newGraphQL(graphQLSchema).build();
}
 
Example #27
Source File: GraphQLFactory.java    From micronaut-graphql with Apache License 2.0 5 votes vote down vote up
@Bean
@Singleton
public GraphQL graphQL(ResourceResolver resourceResolver,
        MessagesDataFetcher messagesDataFetcher,
        ChatDataFetcher chatDataFetcher,
        StreamDataFetcher streamDataFetcher) {

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

    // Parse the schema.
    TypeDefinitionRegistry typeRegistry = new TypeDefinitionRegistry();

    resourceResolver
            .getResourceAsStream("classpath:schema.graphqls")
            .ifPresent(s -> typeRegistry.merge(schemaParser.parse(new BufferedReader(new InputStreamReader(s)))));

    // Create the runtime wiring.
    RuntimeWiring runtimeWiring = RuntimeWiring
            .newRuntimeWiring()
            .scalar(ExtendedScalars.DateTime)
            .type("QueryRoot", typeWiring -> typeWiring
                    .dataFetcher("messages", messagesDataFetcher))
            .type("MutationRoot", typeWiring -> typeWiring
                    .dataFetcher("chat", chatDataFetcher))
            .type("SubscriptionRoot", typeWiring -> typeWiring
                    .dataFetcher("stream", streamDataFetcher))
            .build();

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

    // Return the GraphQL bean.
    return GraphQL.newGraphQL(graphQLSchema).build();
}
 
Example #28
Source File: NonNullTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsr305NonNull() {
    GraphQLSchema schema = new TestSchemaGenerator().withOperationsFromSingleton(new Jsr305()).generate();
    GraphQLFieldDefinition field = schema.getQueryType().getFieldDefinition("nonNull");
    assertNonNull(field.getType(), Scalars.GraphQLString);
    assertNonNull(field.getArgument("in").getType(), Scalars.GraphQLString);
}
 
Example #29
Source File: QueryValidator.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
public QueryValidator(GraphQLSchema schema) {

        this.schema = schema;
        this.validationErrors = new ArrayList<>();
        this.validator = new Validator();
        this.parser = new Parser();

    }
 
Example #30
Source File: RelayTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testRelayId() {
    GraphQLSchema schema = new GraphQLSchemaGenerator()
            .withOperationsFromSingletons(new BookService())
            .generate();

    assertNotNull(schema.getQueryType().getFieldDefinition("node"));

    String globalId = new Relay().toGlobalId(Book.class.getSimpleName(), "x123");
    GraphQL exe = GraphQL.newGraphQL(schema).build();
    ExecutionResult result = exe.execute("{node(id: \"" + globalId + "\") {id ... on Book {title}}}");
    assertTrue(result.getErrors().isEmpty());
    assertValueAtPathEquals(globalId, result, "node.id");
    assertValueAtPathEquals("Node Book", result, "node.title");
}