graphql.schema.GraphQLObjectType Java Examples

The following examples show how to use graphql.schema.GraphQLObjectType. 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: SchemaBundleTest.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
@Test
public void createSchemaUsingSchemaBundle() {
  final SchemaBundle.Builder schemaBuilder = SchemaBundle.builder();
  schemaBuilder
      .modificationsBuilder()
      .add(
          Type.find("inner")
              .addField(
                  GraphQLFieldDefinition.newFieldDefinition()
                      .name("bazinga")
                      .type(Scalars.GraphQLBigInteger)
                      .build()));
  schemaBuilder
      .queryFieldsBuilder()
      .add(
          GraphQLFieldDefinition.newFieldDefinition()
              .name("bazinga")
              .type(GraphQLObjectType.newObject().name("inner"))
              .build());
  final SchemaBundle schemaBundle = schemaBuilder.build();
  final GraphQLSchema schema = schemaBundle.toSchema();
  assertThat(schema.getQueryType().getFieldDefinitions()).hasSize(1);
  assertThat(schema.getQueryType().getFieldDefinitions().get(0).getName()).isEqualTo("bazinga");
}
 
Example #2
Source File: HGQLSchemaWiring.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
private GraphQLObjectType registerGraphQLType(TypeConfig type) {

        String typeName = type.getName();
        String uri = this.hgqlSchema.getTypes().get(typeName).getId();
        String description = "Instances of \"" + uri + "\".";

        List<GraphQLFieldDefinition> builtFields;

        Map<String, FieldOfTypeConfig> fields = type.getFields();

        Set<String> fieldNames = fields.keySet();

        builtFields = fieldNames.stream()
                .map(fieldName -> registerGraphQLField(type.getField(fieldName)))
                .collect(Collectors.toList());

        builtFields.add(getidField());
        builtFields.add(gettypeField());

        return newObject()
                .name(typeName)
                .description(description)
                .fields(builtFields)
                .build();
    }
 
Example #3
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 #4
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private void addMutations(GraphQLSchema.Builder schemaBuilder) {

        if (schema.hasMutations()) {
            GraphQLObjectType.Builder mutationBuilder = GraphQLObjectType.newObject()
                    .name(MUTATION)
                    .description("Mutation root");

            Set<Operation> mutations = schema.getMutations();
            for (Operation mutationOperation : mutations) {
                GraphQLFieldDefinition graphQLFieldDefinition = createGraphQLFieldDefinitionFromOperation(MUTATION,
                        mutationOperation);
                mutationBuilder = mutationBuilder.field(graphQLFieldDefinition);
            }

            GraphQLObjectType mutation = mutationBuilder.build();
            if (mutation.getFieldDefinitions() != null && !mutation.getFieldDefinitions().isEmpty()) {
                schemaBuilder.mutation(mutation);
            }
        }
    }
 
Example #5
Source File: RelayImpl.java    From glitr with MIT License 6 votes vote down vote up
@Override
public GraphQLObjectType connectionType(String name, GraphQLObjectType edgeType, List<GraphQLFieldDefinition> connectionFields) {
    return newObject()
            .name(name + "Connection")
            .description("A connection to a list of items.")
            .field(newFieldDefinition()
                    .name("edges")
                    .type(new GraphQLConnectionList(edgeType))
                    .build())
            .field(newFieldDefinition()
                    .name("pageInfo")
                    .type(new GraphQLNonNull(pageInfoType))
                    .definition(new GlitrFieldDefinition(name, Sets.newHashSet(new GlitrMetaDefinition(COMPLEXITY_IGNORE_KEY, true))))
                    .build())
            .fields(connectionFields)
            .build();
}
 
Example #6
Source File: InputFieldFactory.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void createField(final Document contentTypeDefinition, final Node contentTypeField,
                        final String contentTypeFieldId, final String parentGraphQLTypeName,
                        final GraphQLObjectType.Builder parentGraphQLType, final String graphQLFieldName,
                        final GraphQLFieldDefinition.Builder graphQLField) {
    if (Boolean.parseBoolean(XmlUtils.selectSingleNodeValue(contentTypeField, tokenizeXPath))) {
        // Add the tokenized field as string with text filters
        parentGraphQLType.field(GraphQLFieldDefinition.newFieldDefinition()
            .name(StringUtils.substringBeforeLast(graphQLFieldName, FIELD_SEPARATOR) + FIELD_SUFFIX_TOKENIZED)
            .description("Tokenized version of " + contentTypeFieldId)
            .type(GraphQLString)
            .argument(TEXT_FILTER));
    }

    // Add the original according to the postfix
    setTypeFromFieldName(contentTypeFieldId, graphQLField);
}
 
Example #7
Source File: EnumMapToObjectTypeAdapter.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
protected GraphQLObjectType toGraphQLType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLObjectType.Builder builder = GraphQLObjectType.newObject()
            .name(typeName)
            .description(buildContext.typeInfoGenerator.generateTypeDescription(javaType, buildContext.messageBundle));

    Enum<E>[] keys = ClassUtils.<E>getRawType(getElementType(javaType, 0).getType()).getEnumConstants();
    Arrays.stream(keys).forEach(enumValue -> {
        String fieldName = enumMapper.getValueName(enumValue, buildContext.messageBundle);
        TypedElement element = new TypedElement(getElementType(javaType, 1), ClassUtils.getEnumConstantField(enumValue));
        buildContext.codeRegistry.dataFetcher(FieldCoordinates.coordinates(typeName, fieldName), (DataFetcher) e -> ((Map)e.getSource()).get(enumValue));
        builder.field(GraphQLFieldDefinition.newFieldDefinition()
                .name(fieldName)
                .description(enumMapper.getValueDescription(enumValue, buildContext.messageBundle))
                .deprecate(enumMapper.getValueDeprecationReason(enumValue, buildContext.messageBundle))
                .type(env.forElement(element).toGraphQLType(element.getJavaType()))
                .build());
    });
    return builder.build();
}
 
Example #8
Source File: OperationMapper.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a resolver for the <em>node</em> query as defined by the Relay GraphQL spec.
 * <p>This query only takes a singe argument called "id" of type String, and returns the object implementing the
 * <em>Node</em> interface to which the given id corresponds.</p>
 *
 * @param nodeQueriesByType A map of all queries whose return types implement the <em>Node</em> interface, keyed
 *                          by their corresponding GraphQL type name
 * @param relay Relay helper
 *
 * @return The node query resolver
 */
private DataFetcher<?> createNodeResolver(Map<String, String> nodeQueriesByType, Relay relay) {
    return env -> {
        String typeName;
        try {
            typeName = relay.fromGlobalId(env.getArgument(GraphQLId.RELAY_ID_FIELD_NAME)).getType();
        } catch (Exception e) {
            throw new IllegalArgumentException(env.getArgument(GraphQLId.RELAY_ID_FIELD_NAME) + " is not a valid Relay node ID");
        }
        if (!nodeQueriesByType.containsKey(typeName)) {
            throw new IllegalArgumentException(typeName + " is not a Relay node type or no registered query can fetch it by ID");
        }
        final GraphQLObjectType queryRoot = env.getGraphQLSchema().getQueryType();
        final GraphQLFieldDefinition nodeQueryForType = queryRoot.getFieldDefinition(nodeQueriesByType.get(typeName));

        return env.getGraphQLSchema().getCodeRegistry().getDataFetcher(queryRoot, nodeQueryForType).get(env);
    };
}
 
Example #9
Source File: EntityImageFetcher.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public TypedValue get(DataFetchingEnvironment env) {
  if (env.getSource() instanceof SubjectReference) {
    SubjectReference source = env.getSource();
    DataSet dataSet = source.getDataSet();

    if (env.getParentType() instanceof GraphQLObjectType) {
      String type = getDirectiveArgument((GraphQLObjectType) env.getParentType(), "rdfType", "uri").orElse(null);

      Optional<TypedValue> summaryProperty = summaryPropDataRetriever.createSummaryProperty(source, dataSet, type);
      if (summaryProperty.isPresent()) {
        return summaryProperty.get();
      }
    }
  }
  return null;
}
 
Example #10
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 #11
Source File: HGQLSchemaWiring.java    From hypergraphql with Apache License 2.0 6 votes vote down vote up
private GraphQLObjectType registerGraphQLQueryType(TypeConfig type) {

        String typeName = type.getName();
        String description = "Top queryable predicates. " +
                "_GET queries return all objects of a given type, possibly restricted by limit and offset values. " +
                "_GET_BY_ID queries require a set of URIs to be specified.";

        List<GraphQLFieldDefinition> builtFields = new ArrayList<>();

        Map<String, FieldOfTypeConfig> fields = type.getFields();

        Set<String> fieldNames = fields.keySet();

        for (String fieldName : fieldNames) {
            builtFields.add(registerGraphQLQueryField(type.getField(fieldName)));
        }

        return newObject()
                .name(typeName)
                .description(description)
                .fields(builtFields)
                .build();
    }
 
Example #12
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 #13
Source File: ProtoRegistry.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
/** Applies the supplied modifications to the GraphQLTypes. */
private static BiMap<String, GraphQLType> modifyTypes(
    BiMap<String, GraphQLType> mapping,
    ImmutableListMultimap<String, TypeModification> modifications) {
  BiMap<String, GraphQLType> result = HashBiMap.create(mapping.size());
  for (String key : mapping.keySet()) {
    if (mapping.get(key) instanceof GraphQLObjectType) {
      GraphQLObjectType val = (GraphQLObjectType) mapping.get(key);
      if (modifications.containsKey(key)) {
        for (TypeModification modification : modifications.get(key)) {
          val = modification.apply(val);
        }
      }
      result.put(key, val);
    } else {
      result.put(key, mapping.get(key));
    }
  }
  return result;
}
 
Example #14
Source File: GraphQLSchemaBuilder.java    From graphql-jpa with MIT License 6 votes vote down vote up
GraphQLObjectType getObjectType(EmbeddableType<?> embeddableType) {
	
    if (embeddableCache.containsKey(embeddableType))
        return embeddableCache.get(embeddableType);

    String embeddableName= embeddableType.getJavaType().getSimpleName();
    GraphQLObjectType answer = GraphQLObjectType.newObject()
            .name(embeddableName)
            .description(getSchemaDocumentation(embeddableType.getJavaType()))
            .fields(embeddableType.getAttributes().stream().filter(this::isNotIgnored).flatMap(this::getObjectField).collect(Collectors.toList()))
            .build();

    embeddableCache.put(embeddableType, answer);

    return answer;
}
 
Example #15
Source File: EntityTitleFetcher.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public TypedValue get(DataFetchingEnvironment env) {
  if (env.getSource() instanceof SubjectReference) {
    SubjectReference source = env.getSource();
    DataSet dataSet = source.getDataSet();

    if (env.getParentType() instanceof GraphQLObjectType) {
      String type = getDirectiveArgument((GraphQLObjectType) env.getParentType(), "rdfType", "uri").orElse(null);

      Optional<TypedValue> summaryProperty = summaryPropDataRetriever.createSummaryProperty(source, dataSet, type);
      if (summaryProperty.isPresent()) {
        return summaryProperty.get();
      }
    }

    // fallback to the uri if no summary props can be found for the title
    return TypedValue.create(source.getSubjectUri(), STRING, dataSet);

  }
  return null;
}
 
Example #16
Source File: EntityDescriptionFetcher.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public TypedValue get(DataFetchingEnvironment env) {
  if (env.getSource() instanceof SubjectReference) {
    SubjectReference source = env.getSource();
    DataSet dataSet = source.getDataSet();

    if (env.getParentType() instanceof GraphQLObjectType) {
      String type = getDirectiveArgument((GraphQLObjectType) env.getParentType(), "rdfType", "uri").orElse(null);

      Optional<TypedValue> summaryProperty = summaryPropDataRetriever.createSummaryProperty(source, dataSet, type);
      if (summaryProperty.isPresent()) {
        return summaryProperty.get();
      }
    }
  }
  return null;
}
 
Example #17
Source File: RelayTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Test
public void testDirectNodeQuery() {
    GraphQLSchema schema = new GraphQLSchemaGenerator()
            .withOperationsFromSingletons(new BookService(), new DescriptorService())
            .generate();

    assertNotNull(schema.getQueryType().getFieldDefinition("node"));
    assertTrue(GraphQLUtils.isRelayId(((GraphQLObjectType)schema.getType("Descriptor")).getFieldDefinition("id")));
    assertTrue(GraphQLUtils.isRelayId((schema.getQueryType().getFieldDefinition("descriptor").getArgument("id"))));

    GraphQL exe = GraphQL.newGraphQL(schema).build();
    ExecutionResult result = exe.execute("{node(id: \"Qm9vazprZXds\") {id}}");
    assertNoErrors(result);
    result = exe.execute("{node(id: \"Qm9vazp7InRpdGxlIjoiVGhlIGtleSBib29rIiwiaWQiOiI3NzcifQ==\") {id ... on Descriptor {text}}}");
    assertNoErrors(result);
}
 
Example #18
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 #19
Source File: GraphQLHelloWorldTest.java    From research-graphql with MIT License 6 votes vote down vote up
@Test
public void testGraphQl() {
    GraphQLObjectType queryType = newObject()
            .name("helloWorldQuery")
            .field(newFieldDefinition()
                    .type(GraphQLString)
                    .name("hello")
                    .staticValue("world"))
            .build();

    GraphQLSchema schema = GraphQLSchema.newSchema()
            .query(queryType)
            .build();

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

    Map<String, Object> result = graphQL.execute("{hello}").getData();
    System.out.println(result);
    // Prints: {hello=world}
}
 
Example #20
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 #21
Source File: ProtoToGqlTest.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Test
public void convertShouldWorkForMessage() {
  GraphQLObjectType result =
      ProtoToGql.convert(Proto1.getDescriptor(), null, SchemaOptions.defaultOptions());
  assertThat(result.getName())
      .isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto1");
  assertThat(result.getFieldDefinitions()).hasSize(7);
}
 
Example #22
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
public FederationSdlPrinter(Options options) {
    this.options = options;
    printers.put(GraphQLSchema.class, schemaPrinter());
    printers.put(GraphQLObjectType.class, objectPrinter());
    printers.put(GraphQLEnumType.class, enumPrinter());
    printers.put(GraphQLScalarType.class, scalarPrinter());
    printers.put(GraphQLInterfaceType.class, interfacePrinter());
    printers.put(GraphQLUnionType.class, unionPrinter());
    printers.put(GraphQLInputObjectType.class, inputObjectPrinter());
}
 
Example #23
Source File: InterfaceMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private Optional<GraphQLObjectType> getImplementingType(AnnotatedType implType, TypeMappingEnvironment env) {
    return Optional.of(implType)
            .filter(impl -> !interfaceStrategy.supports(impl))
            .map(impl -> env.operationMapper.toGraphQLType(impl, env))
            .filter(impl -> impl instanceof GraphQLObjectType)
            .map(impl -> (GraphQLObjectType) impl);
}
 
Example #24
Source File: GraphQLSchemaBuilder.java    From graphql-jpa with MIT License 5 votes vote down vote up
GraphQLObjectType getObjectType(EntityType<?> entityType) {
    if (entityCache.containsKey(entityType))
        return entityCache.get(entityType);

    GraphQLObjectType answer = GraphQLObjectType.newObject()
            .name(entityType.getName())
            .description(getSchemaDocumentation(entityType.getJavaType()))
            .fields(entityType.getAttributes().stream().filter(this::isNotIgnored).flatMap(this::getObjectField).collect(Collectors.toList()))
            .build();

    entityCache.put(entityType, answer);

    return answer;
}
 
Example #25
Source File: ObjectTypeMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLObjectType toGraphQLType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLObjectType.Builder typeBuilder = newObject()
            .name(typeName)
            .description(buildContext.typeInfoGenerator.generateTypeDescription(javaType, buildContext.messageBundle));

    List<GraphQLFieldDefinition> fields = getFields(typeName, javaType, env);
    fields.forEach(typeBuilder::field);

    List<GraphQLNamedOutputType> interfaces = getInterfaces(javaType, fields, env);
    interfaces.forEach(inter -> {
        if (inter instanceof GraphQLInterfaceType) {
            typeBuilder.withInterface((GraphQLInterfaceType) inter);
        } else {
            typeBuilder.withInterface((GraphQLTypeReference) inter);
        }
    });

    typeBuilder.withDirective(Directives.mappedType(javaType));
    buildContext.directiveBuilder.buildObjectTypeDirectives(javaType, buildContext.directiveBuilderParams()).forEach(directive ->
            typeBuilder.withDirective(env.operationMapper.toGraphQLDirective(directive, buildContext)));
    typeBuilder.comparatorRegistry(buildContext.comparatorRegistry(javaType));

    GraphQLObjectType type = typeBuilder.build();
    interfaces.forEach(inter -> buildContext.typeRegistry.registerCovariantType(inter.getName(), javaType, type));
    return type;
}
 
Example #26
Source File: DirectiveRetriever.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
public static Optional<String> getDirectiveArgument(GraphQLObjectType parentType, String directiveName,
                                                    String argumentName) {
  return Optional.ofNullable(parentType.getDefinition().getDirective(directiveName))
    .map(d -> d.getArgument(argumentName))
    .map(v -> (StringValue) v.getValue())
    .map(StringValue::getValue);
}
 
Example #27
Source File: GraphQLUtils.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
public static boolean isRelayConnectionType(GraphQLType type) {
    if (!(type instanceof GraphQLObjectType)) {
        return false;
    }
    GraphQLObjectType objectType = (GraphQLObjectType) type;
    return !objectType.getName().equals(CONNECTION) && objectType.getName().endsWith(CONNECTION)
            && objectType.getFieldDefinition(EDGES) != null && objectType.getFieldDefinition(PAGE_INFO) != null;
}
 
Example #28
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 #29
Source File: DirectiveTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testSchemaDirectives() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new ServiceWithDirectives())
            .generate();

    GraphQLFieldDefinition scalarField = schema.getQueryType().getFieldDefinition("scalar");
    assertDirective(scalarField, "fieldDef", "fieldDef");

    GraphQLScalarType scalarResult = (GraphQLScalarType) scalarField.getType();
    assertDirective(scalarResult, "scalar", "scalar");

    graphql.schema.GraphQLArgument argument = scalarField.getArgument("in");
    assertDirective(argument, "argDef", "argument");

    GraphQLInputObjectType inputType = (GraphQLInputObjectType) argument.getType();
    assertDirective(inputType, "inputObjectType", "input");
    graphql.schema.GraphQLArgument directiveArg = DirectivesUtil.directiveWithArg(inputType.getDirectives(), "inputObjectType", "value").get();
    Optional<graphql.schema.GraphQLArgument> metaArg = DirectivesUtil.directiveWithArg(directiveArg.getDirectives(), "meta", "value");
    assertTrue(metaArg.isPresent());
    assertEquals("meta", metaArg.get().getValue());

    GraphQLInputObjectField inputField = inputType.getField("value");
    assertDirective(inputField, "inputFieldDef", "inputField");

    GraphQLFieldDefinition objField = schema.getQueryType().getFieldDefinition("obj");
    GraphQLObjectType objResult = (GraphQLObjectType) objField.getType();
    assertDirective(objResult, "objectType", "object");

    GraphQLFieldDefinition innerField = objResult.getFieldDefinition("value");
    assertDirective(innerField, "fieldDef", "field");
}
 
Example #30
Source File: TypeGeneratorListOfListTest.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
@Test
public void testCanonicalListOfList() {
    logger.debug("testCanonicalListOfList");
    List<List<Integer>> listOfListOfInts = new ArrayList<List<Integer>>() {{
        add(new ArrayList<Integer>() {{
            add(0);
        }});
    }};
    
    GraphQLObjectType queryType = newObject()
            .name("testQuery")
            .field(newFieldDefinition()
                    .type(new GraphQLList(new GraphQLList(Scalars.GraphQLInt)))
                    .name("testObj")
                    .staticValue(listOfListOfInts)
                    .build())
            .build();
    GraphQLSchema listTestSchema = GraphQLSchema.newSchema()
            .query(queryType)
            .build();
    
    String queryString = 
    "{" +
    "  testObj" +
    "}";
    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(List.class));
    assertThat(((List<List<Integer>>) testObj),
            equalTo(listOfListOfInts));
    
}