graphql.schema.GraphQLOutputType Java Examples

The following examples show how to use graphql.schema.GraphQLOutputType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private GraphQLOutputType createGraphQLOutputType(Field field) {
    GraphQLOutputType graphQLOutputType = referenceGraphQLOutputType(field);

    // Collection
    if (field.hasArray()) {
        Array array = field.getArray();
        // Mandatory in the collection
        if (array.isNotEmpty()) {
            graphQLOutputType = GraphQLNonNull.nonNull(graphQLOutputType);
        }
        // Collection depth
        for (int i = 0; i < array.getDepth(); i++) {
            graphQLOutputType = GraphQLList.list(graphQLOutputType);
        }
    }

    // Mandatory
    if (field.isNotNull()) {
        graphQLOutputType = GraphQLNonNull.nonNull(graphQLOutputType);
    }

    return graphQLOutputType;
}
 
Example #2
Source File: FullTypeGenerator.java    From graphql-java-type-generator with MIT License 6 votes vote down vote up
protected GraphQLOutputType generateOutputType(Object object) {
    //An enum is a special case in both java and graphql,
    //and must be checked for while generating other kinds of types
    GraphQLEnumType enumType = generateEnumType(object);
    if (enumType != null) {
        return enumType;
    }
    
    List<GraphQLFieldDefinition> fields = getOutputFieldDefinitions(object);
    if (fields == null || fields.isEmpty()) {
        return null;
    }
    
    String typeName = getGraphQLTypeNameOrIdentityCode(object);
    GraphQLObjectType.Builder builder = newObject()
            .name(typeName)
            .fields(fields)
            .description(getTypeDescription(object));
    
    GraphQLInterfaceType[] interfaces = getInterfaces(object);
    if (interfaces != null) {
        builder.withInterfaces(interfaces);
    }
    return builder.build();
}
 
Example #3
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 #4
Source File: MapToListTypeAdapter.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private GraphQLOutputType mapEntry(GraphQLOutputType keyType, GraphQLOutputType valueType, BuildContext buildContext) {
    String typeName = "mapEntry_" + getTypeName(keyType) + "_" + getTypeName(valueType);
    if (buildContext.typeCache.contains(typeName)) {
        return new GraphQLTypeReference(typeName);
    }
    buildContext.typeCache.register(typeName);

    return newObject()
            .name(typeName)
            .description("Map entry")
            .field(newFieldDefinition()
                    .name("key")
                    .description("Map key")
                    .type(keyType)
                    .build())
            .field(newFieldDefinition()
                    .name("value")
                    .description("Map value")
                    .type(valueType)
                    .build())
            .build();
}
 
Example #5
Source File: OperationMapper.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private GraphQLFieldDefinition toGraphQLField(Operation operation, BuildContext buildContext) {
    GraphQLOutputType type = toGraphQLType(operation.getJavaType(), new TypeMappingEnvironment(operation.getTypedElement(), this, buildContext));
    GraphQLFieldDefinition.Builder fieldBuilder = newFieldDefinition()
            .name(operation.getName())
            .description(operation.getDescription())
            .deprecate(operation.getDeprecationReason())
            .type(type)
            .withDirective(Directives.mappedOperation(operation))
            .withDirectives(toGraphQLDirectives(operation.getTypedElement(), buildContext.directiveBuilder::buildFieldDefinitionDirectives, buildContext));

    List<GraphQLArgument> arguments = operation.getArguments().stream()
            .filter(OperationArgument::isMappable)
            .map(argument -> toGraphQLArgument(argument, buildContext))
            .collect(Collectors.toList());
    fieldBuilder.arguments(arguments);
    if (GraphQLUtils.isRelayConnectionType(type) && buildContext.relayMappingConfig.strictConnectionSpec) {
        validateConnectionSpecCompliance(operation.getName(), arguments, buildContext.relay);
    }

    return buildContext.transformers.transform(fieldBuilder.build(), operation, this, buildContext);
}
 
Example #6
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 #7
Source File: UnionTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
public void testInlineUnion() {
    InlineUnionService unionService = new InlineUnionService();

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

    GraphQLOutputType fieldType = schema.getQueryType().getFieldDefinition("union").getType();
    assertNonNull(fieldType, GraphQLList.class);
    GraphQLType list = ((graphql.schema.GraphQLNonNull) fieldType).getWrappedType();
    assertListOf(list, GraphQLList.class);
    GraphQLType map = ((GraphQLList) list).getWrappedType();
    assertMapOf(map, GraphQLUnionType.class, GraphQLUnionType.class);
    GraphQLObjectType entry = (GraphQLObjectType) GraphQLUtils.unwrap(map);
    GraphQLUnionType key = (GraphQLUnionType) entry.getFieldDefinition("key").getType();
    GraphQLNamedOutputType value = (GraphQLNamedOutputType) entry.getFieldDefinition("value").getType();
    assertEquals("Simple_One_Two", key.getName());
    assertEquals("nice", key.getDescription());
    assertEquals(value.getName(), "Education_Street");
    assertUnionOf(key, schema.getType("SimpleOne"), schema.getType("SimpleTwo"));
    assertUnionOf(value, schema.getType("Education"), schema.getType("Street"));
}
 
Example #8
Source File: TypeGeneratorListOfListTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testGeneratedListOfListOfList() {
    logger.debug("testGeneratedListOfListOfList");
    Object objectType = generator.getOutputType(ClassWithListOfListOfList.class);
    Assert.assertThat(objectType, instanceOf(GraphQLObjectType.class));
    Assert.assertThat(objectType, not(instanceOf(GraphQLList.class)));
    GraphQLFieldDefinition field = ((GraphQLObjectType) objectType)
            .getFieldDefinition("listOfListOfListOfInts");
    
    Assert.assertThat(field, notNullValue());
    GraphQLOutputType listType = field.getType();
    Assert.assertThat(listType, instanceOf(GraphQLList.class));
    GraphQLType wrappedType = ((GraphQLList) listType).getWrappedType();
    assertListOfListOfInt(wrappedType);
}
 
Example #9
Source File: TypeGeneratorGenericsTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testGeneratedListOfParam() {
    logger.debug("testGeneratedListOfParam");
    Object objectType = generator.getOutputType(ClassWithListOfGenerics.class);
    Assert.assertThat(objectType, instanceOf(GraphQLObjectType.class));
    Assert.assertThat(objectType, not(instanceOf(GraphQLList.class)));
    GraphQLFieldDefinition field = ((GraphQLObjectType) objectType)
            .getFieldDefinition("listOfParamOfInts");
    
    Assert.assertThat(field, notNullValue());
    GraphQLOutputType listType = field.getType();
    Assert.assertThat(listType, instanceOf(GraphQLList.class));
    GraphQLType wrappedType = ((GraphQLList) listType).getWrappedType();
    Assert.assertThat(wrappedType, instanceOf(GraphQLObjectType.class));
}
 
Example #10
Source File: TypeGeneratorTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testClassesWithInterfaces() {
    logger.debug("testClassesWithInterfaces");
    Object interfaceType = generator.getOutputType(InterfaceChild.class);
    assertThat(interfaceType, instanceOf(GraphQLOutputType.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();
    
    final ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> expectedQueryData = mapper
            .convertValue(new InterfaceImpl(), Map.class);
    assertThat(((Map<String, Object>)resultMap.get("testObj")),
            equalTo(expectedQueryData));
    assertThat(((Map<String, Object>)resultMap.get("testObj")).size(),
            is(2));
}
 
Example #11
Source File: TypeGeneratorListOfListTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
public static void assertClassWithListOfList(Object objectType) {
    Assert.assertThat(objectType, instanceOf(GraphQLObjectType.class));
    Assert.assertThat(objectType, not(instanceOf(GraphQLList.class)));
    GraphQLFieldDefinition field = ((GraphQLObjectType) objectType)
            .getFieldDefinition("listOfListOfInts");
    
    Assert.assertThat(field, notNullValue());
    GraphQLOutputType outputType = field.getType();
    assertListOfListOfInt(outputType);
}
 
Example #12
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 #13
Source File: GaxSchemaModule.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
private GraphQLOutputType getReturnType(ParameterizedType parameterizedType)
    throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  Class<? extends Message> responseClass =
      (Class<? extends Message>) parameterizedType.getActualTypeArguments()[1];
  Descriptors.Descriptor responseDescriptor =
      (Descriptors.Descriptor) responseClass.getMethod("getDescriptor").invoke(null);
  addExtraType(responseDescriptor);
  return ProtoToGql.getReference(responseDescriptor);
}
 
Example #14
Source File: TypeGeneratorRawArrayTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testRawArray() {
    logger.debug("testRawArray");
    Object objectType = generator.getOutputType(ClassWithArray.class);
    assertListOfInt(objectType);
    assertQueryOnListOfInt((GraphQLOutputType) objectType, new ClassWithArray());
}
 
Example #15
Source File: TypeGeneratorRawArrayTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void assertQueryOnListOfInt(GraphQLOutputType outputType, Object staticValue) {
    GraphQLObjectType queryType = newObject()
            .name("testQuery")
            .field(newFieldDefinition()
                    .type(outputType)
                    .name("testObj")
                    .staticValue(staticValue)
                    .build())
            .build();
    GraphQLSchema listTestSchema = GraphQLSchema.newSchema()
            .query(queryType)
            .build();
    
    String queryString = 
    "{" +
    "  testObj {" +
    "    integers" +
    "  }" +
    "}";
    ExecutionResult queryResult = new GraphQL(listTestSchema).execute(queryString);
    assertThat(queryResult.getErrors(), is(empty()));
    Map<String, Object> resultMap = (Map<String, Object>) queryResult.getData();
    logger.debug("assertQueryOnListOfInt resultMap {}",
            TypeGeneratorTest.prettyPrint(resultMap));
    
    Object testObj = resultMap.get("testObj");
    final ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> expectedQueryData = mapper
            .convertValue(staticValue, Map.class);
    Assert.assertThat((Map<String, Object>)testObj,
            equalTo(expectedQueryData));
}
 
Example #16
Source File: TypeGeneratorRawArrayTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testArrayList() {
    logger.debug("testArrayList");
    Object objectType = generator.getOutputType(ClassWithArrayList.class);
    assertListOfInt(objectType);
    assertQueryOnListOfInt((GraphQLOutputType) objectType, new ClassWithArrayList());
}
 
Example #17
Source File: RejoinerIntegrationTest.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Test
public void schemaShouldList() {
  GraphQLOutputType listOfStuff =
      schema.getQueryType().getFieldDefinition("listOfStuff").getType();
  assertThat(listOfStuff).isInstanceOf(GraphQLList.class);
  assertThat(((GraphQLList) listOfStuff).getWrappedType()).isInstanceOf(GraphQLNonNull.class);
}
 
Example #18
Source File: TypeGeneratorRawArrayTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
public void assertListOfInt(Object objectType) {
    Assert.assertThat(objectType, instanceOf(GraphQLObjectType.class));
    Assert.assertThat(objectType, not(instanceOf(GraphQLList.class)));
    GraphQLFieldDefinition fieldDefinition = ((GraphQLObjectType) objectType).getFieldDefinition("integers");
    Assert.assertThat(fieldDefinition, notNullValue());
    GraphQLOutputType outputType = fieldDefinition.getType();

    Assert.assertThat(outputType, CoreMatchers.instanceOf(GraphQLList.class));
    GraphQLType wrappedType = ((GraphQLList) outputType).getWrappedType();
    Assert.assertThat(wrappedType, instanceOf(GraphQLScalarType.class));
    Assert.assertThat((GraphQLScalarType)wrappedType, is(Scalars.GraphQLInt));
}
 
Example #19
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
private TypePrinter<GraphQLUnionType> unionPrinter() {
    return (out, type, visibility) -> {
        if (isIntrospectionType(type)) {
            return;
        }

        GraphqlTypeComparatorEnvironment environment = GraphqlTypeComparatorEnvironment.newEnvironment()
                .parentType(GraphQLUnionType.class)
                .elementType(GraphQLOutputType.class)
                .build();
        Comparator<? super GraphQLSchemaElement> comparator = options.comparatorRegistry.getComparator(environment);

        if (shouldPrintAsAst(type.getDefinition())) {
            printAsAst(out, type.getDefinition(), type.getExtensionDefinitions());
        } else {
            printComments(out, type, "");
            out.format("union %s%s = ", type.getName(), directivesString(GraphQLUnionType.class, type.getDirectives()));
            List<GraphQLNamedOutputType> types = type.getTypes()
                    .stream()
                    .sorted(comparator)
                    .collect(toList());
            for (int i = 0; i < types.size(); i++) {
                GraphQLNamedOutputType objectType = types.get(i);
                if (i > 0) {
                    out.format(" | ");
                }
                out.format("%s", objectType.getName());
            }
            out.format("\n\n");
        }
    };
}
 
Example #20
Source File: TypeGeneratorWithFieldsGenIntegrationTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testListOfList() {
    logger.debug("testListOfList");
    Object listType = testContext.getOutputType(ClassWithListOfList.class);
    Assert.assertThat(listType, instanceOf(GraphQLOutputType.class));
    
    GraphQLObjectType queryType = newObject()
            .name("testQuery")
            .field(newFieldDefinition()
                    .type((GraphQLOutputType) listType)
                    .name("testObj")
                    .staticValue(new ClassWithListOfList())
                    .build())
            .build();
    GraphQLSchema listTestSchema = GraphQLSchema.newSchema()
            .query(queryType)
            .build();
    
    String queryString = 
    "{"
    + "  testObj {"
    + "    listOfListOfInts"
    + "  }"
    + "}";
    ExecutionResult queryResult = new GraphQL(listTestSchema).execute(queryString);
    assertThat(queryResult.getErrors(), is(empty()));
    Map<String, Object> resultMap = (Map<String, Object>) queryResult.getData();
    logger.debug("testCanonicalListOfList resultMap {}",
            TypeGeneratorTest.prettyPrint(resultMap));
    Object testObj = resultMap.get("testObj");
    Assert.assertThat(testObj, instanceOf(Map.class));
    Object listObj = ((Map<String, Object>) testObj).get("listOfListOfInts");
    Assert.assertThat(listObj, instanceOf(List.class));
}
 
Example #21
Source File: UnionTypeMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLOutputType toGraphQLType(AnnotatedType javaType, Set<Class<? extends TypeMapper>> mappersToSkip, TypeMappingEnvironment env) {
    GraphQLUnion annotation = javaType.getAnnotation(GraphQLUnion.class);
    List<AnnotatedType> possibleJavaTypes = getPossibleJavaTypes(javaType, env.buildContext);
    final String name = env.buildContext.typeInfoGenerator.generateTypeName(javaType, env.buildContext.messageBundle);
    return toGraphQLUnion(name, annotation.description(), javaType, possibleJavaTypes, env);
}
 
Example #22
Source File: CachingMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLOutputType toGraphQLType(AnnotatedType javaType, Set<Class<? extends TypeMapper>> mappersToSkip, TypeMappingEnvironment env) {
    String typeName = getTypeName(javaType, env.buildContext);
    if (env.buildContext.typeCache.contains(typeName)) {
        return new GraphQLTypeReference(typeName);
    }
    env.buildContext.typeCache.register(typeName);
    return toGraphQLType(typeName, javaType, env);
}
 
Example #23
Source File: MapToListTypeAdapter.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLOutputType toGraphQLType(AnnotatedType javaType, Set<Class<? extends TypeMapper>> mappersToSkip, TypeMappingEnvironment env) {
    return new GraphQLList(new GraphQLNonNull(
            mapEntry(
                    //MapEntry fields are artificial - no Java element is backing them
                    env.forElement(null).toGraphQLType(getElementType(javaType, 0)),
                    env.forElement(null).toGraphQLType(getElementType(javaType, 1)), env.buildContext)));
}
 
Example #24
Source File: MappedType.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
MappedType(AnnotatedType javaType, GraphQLOutputType graphQLType) {
    if (!(graphQLType instanceof GraphQLTypeReference || graphQLType instanceof GraphQLObjectType)) {
        throw new IllegalArgumentException("Implementation types can only be object types or references to object types");
    }
    this.rawJavaType = ClassUtils.getRawType(javaType.getType());
    this.javaType = javaType;
    this.graphQLType = graphQLType;
}
 
Example #25
Source File: ResolvedField.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public ResolvedField(Field field, GraphQLFieldDefinition fieldDefinition, Map<String, Object> arguments, Map<String, ResolvedField> children) {
    this.name = field.getAlias() != null ? field.getAlias() : field.getName();
    this.field = field;
    this.fieldDefinition = fieldDefinition;
    this.fieldType = (GraphQLOutputType) GraphQLUtils.unwrap(fieldDefinition.getType());
    this.arguments = arguments;
    this.children = children;
    this.resolver = findResolver(fieldDefinition, arguments);
}
 
Example #26
Source File: GenericsTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonNullGenerics() {
    GenericItemRepo<@GraphQLNonNull String> nonNullStringService = new GenericItemRepo<>();
    nonNullStringService.addItem("pooch", "Strudel, the poodle");
    nonNullStringService.addItem("booze", "Fire-water");

    GraphQLSchema schemaWithNonNullGenerics = new TestSchemaGenerator()
            .withOperationsFromSingleton(nonNullStringService, nonNullString)
            .withValueMapperFactory(valueMapperFactory)
            .generate();

    GraphQLOutputType itemType = schemaWithNonNullGenerics.getQueryType().getFieldDefinition("item").getType();
    assertNonNull(itemType, Scalars.GraphQLString);

    GraphQLOutputType itemCollectionType = schemaWithNonNullGenerics.getQueryType().getFieldDefinition("allItems").getType();
    assertListOfNonNull(itemCollectionType, Scalars.GraphQLString);

    GraphQLFieldDefinition addOneItem = schemaWithNonNullGenerics.getMutationType().getFieldDefinition("addItem");
    assertEquals(addOneItem.getArguments().size(), 2);
    assertArgumentsPresent(addOneItem, "item", "name");
    assertNonNull(addOneItem.getArgument("item").getType(), Scalars.GraphQLString);

    GraphQLFieldDefinition addManyItems = schemaWithNonNullGenerics.getMutationType().getFieldDefinition("addItems");
    assertEquals(addManyItems.getArguments().size(), 1);
    assertArgumentsPresent(addManyItems, "items");
    assertListOfNonNull(addManyItems.getArgument("items").getType(), Scalars.GraphQLString);

    GraphQL graphQL = GraphQL.newGraphQL(schemaWithNonNullGenerics).build();
    ExecutionResult result = graphQL.execute("{ allItems }");
    assertTrue(ERRORS, result.getErrors().isEmpty());
    assertEquals(new ArrayList<>(nonNullStringService.getAllItems()), ((Map<String, Object>) result.getData()).get("allItems"));
}
 
Example #27
Source File: GenericsTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testWildcardGenerics() {
    GenericItemRepo<@GraphQLNonNull List<? extends Number>> wildcardNumberService = new GenericItemRepo<>();
    wildcardNumberService.addItem("player1", Arrays.asList(12, 13.4, new BigDecimal("4000")));
    wildcardNumberService.addItem("player2", Arrays.asList(new BigDecimal("12.56"), 14.78));

    GraphQLSchema schemaWithGenerics = new TestSchemaGenerator()
            .withOperationsFromSingleton(wildcardNumberService, listOfWildcardNumbers)
            .withValueMapperFactory(valueMapperFactory)
            .generate();

    GraphQLOutputType itemType = schemaWithGenerics.getQueryType().getFieldDefinition("item").getType();
    assertNonNull(itemType, GraphQLList.class);
    assertListOf(((graphql.schema.GraphQLNonNull) itemType).getWrappedType(), Scalars.GraphQLBigDecimal);

    GraphQLOutputType itemCollectionType = schemaWithGenerics.getQueryType().getFieldDefinition("allItems").getType();
    assertListOfNonNull(itemCollectionType, GraphQLList.class);
    assertListOf(((graphql.schema.GraphQLNonNull) ((GraphQLList) itemCollectionType).getWrappedType()).getWrappedType(), Scalars.GraphQLBigDecimal);

    GraphQLFieldDefinition addOneItem = schemaWithGenerics.getMutationType().getFieldDefinition("addItem");
    GraphQLType itemArgType = addOneItem.getArgument("item").getType();
    assertNonNull(itemArgType, GraphQLList.class);
    assertListOf(((graphql.schema.GraphQLNonNull) itemArgType).getWrappedType(), Scalars.GraphQLBigDecimal);

    GraphQL graphQL = GraphQL.newGraphQL(schemaWithGenerics).build();
    ExecutionResult result = graphQL.execute("{ allItems }");
    assertTrue(ERRORS, result.getErrors().isEmpty());
    Object[] expected = wildcardNumberService.getAllItems().toArray();
    Object[] actual = wildcardNumberService.getAllItems().toArray();
    assertArrayEquals(expected, actual);
}
 
Example #28
Source File: GenericsTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testArrayGenerics() {
    GenericItemRepo<@GraphQLNonNull List<Number> @GraphQLNonNull []> arrayNumberService = new GenericItemRepo<>();
    List<Number>[] array1 = (List<Number>[]) new List[1];
    array1[0] = Arrays.asList(12, 13.4, new BigDecimal("4000"));
    List<Number>[] array2 = (List<Number>[]) new List[1];
    array2[0] = Arrays.asList(new BigDecimal("12.56"), 14.78);
    arrayNumberService.addItem("scores1", array1);
    arrayNumberService.addItem("scores2", array2);

    GraphQLSchema schemaWithGenerics = new TestSchemaGenerator()
            .withOperationsFromSingleton(arrayNumberService, arrayOfListsOfNumbers)
            .withValueMapperFactory(valueMapperFactory)
            .generate();

    GraphQLOutputType itemType = schemaWithGenerics.getQueryType().getFieldDefinition("item").getType();
    assertNonNull(itemType, GraphQLList.class);
    GraphQLType inner = ((graphql.schema.GraphQLNonNull) itemType).getWrappedType();
    assertListOf(inner, graphql.schema.GraphQLNonNull.class);
    inner = ((graphql.schema.GraphQLNonNull) ((GraphQLList) inner).getWrappedType()).getWrappedType();
    assertListOf(inner, Scalars.GraphQLBigDecimal);

    GraphQLFieldDefinition addOneItem = schemaWithGenerics.getMutationType().getFieldDefinition("addItem");
    GraphQLType itemArgType = addOneItem.getArgument("item").getType();
    assertNonNull(itemArgType, GraphQLList.class);
    inner = ((graphql.schema.GraphQLNonNull) itemType).getWrappedType();
    assertListOf(inner, graphql.schema.GraphQLNonNull.class);
    inner = ((graphql.schema.GraphQLNonNull) ((GraphQLList) inner).getWrappedType()).getWrappedType();
    assertListOf(inner, Scalars.GraphQLBigDecimal);

    GraphQL graphQL = GraphQL.newGraphQL(schemaWithGenerics).build();
    ExecutionResult result = graphQL.execute("{ allItems }");
    assertTrue(ERRORS, result.getErrors().isEmpty());
    Object[] expected = arrayNumberService.getAllItems().toArray();
    Object[] actual = arrayNumberService.getAllItems().toArray();
    assertArrayEquals(expected, actual);
}
 
Example #29
Source File: GraphQLTypeAssertions.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static void assertMapOf(GraphQLType mapType, Class<? extends GraphQLType> keyType, Class<? extends GraphQLType> valueType) {
    assertEquals(GraphQLList.class, mapType.getClass());
    GraphQLType entry = GraphQLUtils.unwrap(mapType);
    assertTrue(entry instanceof GraphQLObjectType);
    GraphQLOutputType key = ((GraphQLObjectType) entry).getFieldDefinition("key").getType();
    GraphQLOutputType value = ((GraphQLObjectType) entry).getFieldDefinition("value").getType();
    assertTrue(keyType.isAssignableFrom(key.getClass()));
    assertTrue(valueType.isAssignableFrom(value.getClass()));
}
 
Example #30
Source File: MethodDataFetcher.java    From graphql-apigen with Apache License 2.0 5 votes vote down vote up
private boolean isBooleanMethod(GraphQLOutputType outputType) {
    if (outputType == GraphQLBoolean) return true;
    if (outputType instanceof GraphQLNonNull) {
        return ((GraphQLNonNull) outputType).getWrappedType() == GraphQLBoolean;
    }
    return false;
}