graphql.schema.GraphQLEnumType Java Examples

The following examples show how to use graphql.schema.GraphQLEnumType. 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: 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 #2
Source File: GraphQLSchemaBuilder.java    From graphql-jpa with MIT License 6 votes vote down vote up
private GraphQLType getTypeFromJavaType(Class clazz) {
    if (clazz.isEnum()) {
        if (classCache.containsKey(clazz))
            return classCache.get(clazz);

        GraphQLEnumType.Builder enumBuilder = GraphQLEnumType.newEnum().name(clazz.getSimpleName());
        int ordinal = 0;
        for (Enum enumValue : ((Class<Enum>) clazz).getEnumConstants())
            enumBuilder.value(enumValue.name(), ordinal++);

        GraphQLType answer = enumBuilder.build();
        setIdentityCoercing(answer);

        classCache.put(clazz, answer);

        return answer;
    }

    return getBasicAttributeType(clazz);
}
 
Example #3
Source File: OperationInfoTest.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private void testEnumValues(boolean respectJavaDeprecation) {
    GraphQLSchema schema = new GraphQLSchemaGenerator()
            .withOperationsFromSingleton(new BunnyService())
            .withJavaDeprecationRespected(respectJavaDeprecation)
            .generate();

    GraphQLEnumType bunnyType = (GraphQLEnumType) schema.getType("BunnyType");

    assertEquals("Types of bunnies", bunnyType.getDescription());

    assertNotEquals(null, bunnyType.getValue("IntenselyCute"));
    assertFalse(bunnyType.getValue("IntenselyCute").isDeprecated());

    assertFalse(bunnyType.getValue("ADORABLE").isDeprecated());
    assertEquals("Thoroughly adorable", bunnyType.getValue("ADORABLE").getDescription());

    assertTrue(bunnyType.getValue("MEH").isDeprecated());
    assertEquals("Impossible", bunnyType.getValue("MEH").getDeprecationReason());

    assertEquals(respectJavaDeprecation, bunnyType.getValue("AVERAGE").isDeprecated());
    if (respectJavaDeprecation) {
        assertEquals("Deprecated", bunnyType.getValue("AVERAGE").getDeprecationReason());
    }

    assertFalse(bunnyType.getValue("Omg").isDeprecated());
}
 
Example #4
Source File: JavaScriptEvaluator.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
@Override
public int getComplexity(ResolvedField node, int childScore) {
    Resolver resolver = node.getResolver();
    if (resolver == null || Utils.isEmpty(resolver.getComplexityExpression())) {
        GraphQLType fieldType = node.getFieldType();
        if (fieldType instanceof GraphQLScalarType || fieldType instanceof GraphQLEnumType) {
            return 1;
        }
        if (GraphQLUtils.isRelayConnectionType(fieldType)) {
            Integer pageSize = getPageSize(node.getArguments());
            if (pageSize != null) {
                return pageSize * childScore;
            }
        }
        return 1 + childScore;
    }
    Bindings bindings = engine.createBindings();
    bindings.putAll(node.getArguments());
    bindings.put("childScore", childScore);
    try {
        return ((Number) engine.eval(resolver.getComplexityExpression(), bindings)).intValue();
    } catch (Exception e) {
        throw new IllegalArgumentException(String.format("Complexity expression \"%s\" on field %s could not be evaluated",
                resolver.getComplexityExpression(), node.getName()), e);
    }
}
 
Example #5
Source File: TypeGeneratorWithFieldsGenIntegrationTest.java    From graphql-java-type-generator with MIT License 6 votes vote down vote up
@Test
public void testEnum() {
    logger.debug("testEnum");
    Object enumObj = testContext.getOutputType(graphql.java.generator.Enum.class);
    Assert.assertThat(enumObj, instanceOf(GraphQLEnumType.class));
    Matcher<Iterable<GraphQLEnumValueDefinition>> hasItemsMatcher =
            hasItems(
                    hasProperty("name", is("A")),
                    hasProperty("name", is("B")),
                    hasProperty("name", is("C")));
    assertThat(((GraphQLEnumType)enumObj).getValues(), hasItemsMatcher);
    
    enumObj = testContext.getOutputType(graphql.java.generator.EmptyEnum.class);
    Assert.assertThat(enumObj, instanceOf(GraphQLEnumType.class));
    assertThat(((GraphQLEnumType)enumObj).getValues(),
            instanceOf(List.class));
    assertThat(((GraphQLEnumType)enumObj).getValues().size(),
            is(0));
}
 
Example #6
Source File: FullTypeGenerator.java    From graphql-java-type-generator with MIT License 6 votes vote down vote up
protected GraphQLInputType generateInputType(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<GraphQLInputObjectField> fields = getInputFieldDefinitions(object);
    if (fields == null || fields.isEmpty()) {
        return null;
    }
    String typeName = getGraphQLTypeNameOrIdentityCode(object);
    
    GraphQLInputObjectType.Builder builder = new GraphQLInputObjectType.Builder();
    builder.name(typeName);
    builder.fields(fields);
    builder.description(getTypeDescription(object));
    return builder.build();
}
 
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: SchemaToProto.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
private static String toEnum(GraphQLEnumType type) {
  ArrayList<String> values = new ArrayList<>();
  int i = 0;
  for (GraphQLEnumValueDefinition value : type.getValues()) {
    if (value.getName().equals("UNRECOGNIZED")) {
      continue;
    }
    values.add(String.format("%s = %d;", value.getName(), i));
    i++;
  }
  return String.format(
      "message %s {\n %s\n enum Enum {\n%s\n}\n}",
      type.getName(), getJspb(type), Joiner.on("\n").join(values));
}
 
Example #9
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
/**
 * This can print an in memory GraphQL schema back to a logical schema definition
 *
 * @param schema the schema in play
 * @return the logical schema definition
 */
public String print(GraphQLSchema schema) {
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);

    GraphqlFieldVisibility visibility = schema.getCodeRegistry().getFieldVisibility();

    printer(schema.getClass()).print(out, schema, visibility);

    List<GraphQLType> typesAsList = schema.getAllTypesAsList()
            .stream()
            .sorted(Comparator.comparing(GraphQLNamedType::getName))
            .filter(options.getIncludeTypeDefinition())
            .collect(toList());

    printType(out, typesAsList, GraphQLInterfaceType.class, visibility);
    printType(out, typesAsList, GraphQLUnionType.class, visibility);
    printType(out, typesAsList, GraphQLObjectType.class, visibility);
    printType(out, typesAsList, GraphQLEnumType.class, visibility);
    printType(out, typesAsList, GraphQLScalarType.class, visibility);
    printType(out, typesAsList, GraphQLInputObjectType.class, visibility);

    String result = sw.toString();
    if (result.endsWith("\n\n")) {
        result = result.substring(0, result.length() - 1);
    }
    return result;
}
 
Example #10
Source File: GraphQLEnumTypeFactory.java    From glitr with MIT License 5 votes vote down vote up
/**
 * Creates the {@link GraphQLEnumType} dynamically for the given enum
 *
 * @param clazz enum class to be introspected
 * @return {@link GraphQLEnumType} object exposed via graphQL
 */
public static GraphQLEnumType createEnumType(Class clazz) {
    GraphQLEnumType.Builder builder = newEnum()
            .name(clazz.getSimpleName())
            .description(ReflectionUtil.getDescriptionFromAnnotatedElement(clazz));

    for (Object constant : clazz.getEnumConstants()) {
        builder.value(constant.toString(), constant);
    }

    return builder.build();
}
 
Example #11
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 5 votes vote down vote up
private TypePrinter<GraphQLEnumType> enumPrinter() {
    return (out, type, visibility) -> {
        if (isIntrospectionType(type)) {
            return;
        }

        GraphqlTypeComparatorEnvironment environment = GraphqlTypeComparatorEnvironment.newEnvironment()
                .parentType(GraphQLEnumType.class)
                .elementType(GraphQLEnumValueDefinition.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("enum %s%s", type.getName(), directivesString(GraphQLEnumType.class, type.getDirectives()));
            List<GraphQLEnumValueDefinition> values = type.getValues()
                    .stream()
                    .sorted(comparator)
                    .collect(toList());
            if (values.size() > 0) {
                out.format(" {\n");
                for (GraphQLEnumValueDefinition enumValueDefinition : values) {
                    printComments(out, enumValueDefinition, "  ");
                    List<GraphQLDirective> enumValueDirectives = enumValueDefinition.getDirectives();
                    if (enumValueDefinition.isDeprecated()) {
                        enumValueDirectives = addDeprecatedDirectiveIfNeeded(enumValueDirectives);
                    }
                    out.format("  %s%s\n", enumValueDefinition.getName(), directivesString(GraphQLEnumValueDefinition.class, enumValueDirectives));
                }
                out.format("}");
            }
            out.format("\n\n");
        }
    };
}
 
Example #12
Source File: RelayTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtendedConnectionMapping() {
    GraphQLSchema schema = new TestSchemaGenerator()
            .withOperationsFromSingleton(new ExtendedEdgeBookService())
            .generate();

    GraphQLObjectType bookConnection = schema.getObjectType("BookConnection");
    assertEquals(3, bookConnection.getFieldDefinitions().size());
    GraphQLFieldDefinition totalCount = bookConnection.getFieldDefinition("totalCount");
    assertNotNull(totalCount);
    assertNonNull(totalCount.getType(), Scalars.GraphQLLong);

    GraphQLObjectType bookEdge = schema.getObjectType("BookEdge");
    assertEquals(3, bookEdge.getFieldDefinitions().size());
    GraphQLFieldDefinition color = bookEdge.getFieldDefinition("color");
    assertNotNull(color);
    assertTrue(color.getType() instanceof GraphQLEnumType);

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

    ExecutionResult result = exe.execute("{extended(first:10, after:\"20\") {" +
            "   totalCount" +
            "   pageInfo {" +
            "       hasNextPage" +
            "   }," +
            "   edges {" +
            "       color, cursor, node {" +
            "           title" +
            "}}}}");
    assertNoErrors(result);
    assertValueAtPathEquals(100L, result, "extended.totalCount");
    assertValueAtPathEquals("Tesseract", result, "extended.edges.0.node.title");
}
 
Example #13
Source File: Bootstrap.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private void createGraphQLEnumType(EnumType enumType) {
    GraphQLEnumType.Builder enumBuilder = GraphQLEnumType.newEnum()
            .name(enumType.getName())
            .description(enumType.getDescription());
    // Values
    for (String value : enumType.getValues()) {
        enumBuilder = enumBuilder.value(value);
    }
    GraphQLEnumType graphQLEnumType = enumBuilder.build();
    enumMap.put(enumType.getClassName(), graphQLEnumType);
}
 
Example #14
Source File: EnumMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private void addOptions(GraphQLEnumType.Builder enumBuilder, AnnotatedType javaType, OperationMapper operationMapper, BuildContext buildContext) {
    MessageBundle messageBundle = buildContext.messageBundle;
    Arrays.stream((Enum[]) ClassUtils.getRawType(javaType.getType()).getEnumConstants())
            .map(enumConst -> (Enum<?>) enumConst)
            .forEach(enumConst -> enumBuilder.value(GraphQLEnumValueDefinition.newEnumValueDefinition()
                    .name(getValueName(enumConst, messageBundle))
                    .value(enumConst)
                    .description(getValueDescription(enumConst, messageBundle))
                    .deprecationReason(getValueDeprecationReason(enumConst, messageBundle))
                    .withDirectives(getValueDirectives(enumConst, operationMapper, buildContext))
                    .build()));
}
 
Example #15
Source File: EnumMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Override
public GraphQLEnumType toGraphQLType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    BuildContext buildContext = env.buildContext;

    GraphQLEnumType.Builder enumBuilder = newEnum()
            .name(typeName)
            .description(buildContext.typeInfoGenerator.generateEnumTypeDescription(javaType, buildContext.messageBundle));
    buildContext.directiveBuilder.buildEnumTypeDirectives(javaType, buildContext.directiveBuilderParams()).forEach(directive ->
            enumBuilder.withDirective(env.operationMapper.toGraphQLDirective(directive, buildContext)));
    addOptions(enumBuilder, javaType, env.operationMapper, buildContext);
    enumBuilder.comparatorRegistry(buildContext.comparatorRegistry(javaType));
    return enumBuilder.build();
}
 
Example #16
Source File: CachingMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private String getTypeName(AnnotatedType javaType, AnnotatedType graphQLType, TypeInfoGenerator typeInfoGenerator, MessageBundle messageBundle) {
    if (ClassUtils.isSuperClass(GraphQLScalarType.class, graphQLType)) {
        return typeInfoGenerator.generateScalarTypeName(javaType, messageBundle);
    }
    if (ClassUtils.isSuperClass(GraphQLEnumType.class, graphQLType)) {
        return typeInfoGenerator.generateEnumTypeName(javaType, messageBundle);
    }
    if (ClassUtils.isSuperClass(GraphQLInputType.class, graphQLType)) {
        return typeInfoGenerator.generateInputTypeName(javaType, messageBundle);
    }
    return typeInfoGenerator.generateTypeName(javaType, messageBundle);
}
 
Example #17
Source File: RejoinerIntegrationTest.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Test
public void schemaShouldGetAccountWithEnumArgs() {
  GraphQLFieldDefinition getAccount =
      schema.getQueryType().getFieldDefinition("getAccountWithLanguages");
  assertThat(getAccount.getArgument("language").getType()).isInstanceOf(GraphQLEnumType.class);
  assertThat(getAccount.getType()).isInstanceOf(GraphQLObjectType.class);
}
 
Example #18
Source File: FullTypeGenerator.java    From graphql-java-type-generator with MIT License 5 votes vote down vote up
protected GraphQLEnumType generateEnumType(Object object) {
    String typeName = getGraphQLTypeNameOrIdentityCode(object);

    List<GraphQLEnumValueDefinition> enumValues = getEnumValues(object);
    if (enumValues == null) {
        return null;
    }
    GraphQLEnumType.Builder builder = newEnum();
    builder.name(typeName);
    builder.description(getTypeDescription(object));
    for (GraphQLEnumValueDefinition value : enumValues) {
        builder.value(value.getName(), value.getValue(), value.getDescription());
    }
    return builder.build();
}
 
Example #19
Source File: SchemaToProto.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
/** Returns a proto source file for the schema. */
public static String toProto(GraphQLSchema schema) {
  ArrayList<String> messages = new ArrayList<>();

  for (GraphQLType type : getAllTypes(schema)) {
    if (type instanceof GraphQLEnumType) {
      messages.add(toEnum((GraphQLEnumType) type));
    } else if (type instanceof GraphQLObjectType) {
      messages.add(toMessage((GraphQLObjectType) type));
    }
  }

  return HEADER + Joiner.on("\n\n").join(messages);
}
 
Example #20
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 #21
Source File: ProtoToGqlTest.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Test
public void convertShouldWorkForEnums() {
  GraphQLEnumType result =
      ProtoToGql.convert(TestEnum.getDescriptor(), SchemaOptions.defaultOptions());
  assertThat(result.getName())
      .isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto2_TestEnum");
  assertThat(result.getValues()).hasSize(3);
  assertThat(result.getValues().stream().map(GraphQLEnumValueDefinition::getName).toArray())
      .asList()
      .containsExactly("UNKNOWN", "FOO", "BAR");
}
 
Example #22
Source File: ProtoDataFetcher.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Override
public Object get(DataFetchingEnvironment environment) throws Exception {

  final Object source = environment.getSource();
  if (source == null) {
    return null;
  }

  if (source instanceof Message) {
    GraphQLType type = environment.getFieldType();
    if (type instanceof GraphQLEnumType) {
      return ((Message) source).getField(fieldDescriptor).toString();
    }
    return ((Message) source).getField(fieldDescriptor);
  }
  if (environment.getSource() instanceof Map) {
    return ((Map<?, ?>) source).get(convertedFieldName);
  }

  if (method == null) {
    // no synchronization necessary because this line is idempotent
    final String methodNameSuffix =
        fieldDescriptor.isMapField() ? "Map" : fieldDescriptor.isRepeated() ? "List" : "";
    final String methodName =
        "get" + LOWER_CAMEL_TO_UPPER.convert(convertedFieldName) + methodNameSuffix;
    method = source.getClass().getMethod(methodName);
  }
  return method.invoke(source);
}
 
Example #23
Source File: ProtoToGql.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
static GraphQLEnumType convert(
    EnumDescriptor descriptor, SchemaOptions schemaOptions) {
  GraphQLEnumType.Builder builder = GraphQLEnumType.newEnum().name(getReferenceName(descriptor));
  for (EnumValueDescriptor value : descriptor.getValues()) {
    builder.value(
        value.getName(),
        value.getName(),
        schemaOptions.commentsMap().get(value.getFullName()),
        value.getOptions().getDeprecated() ? "deprecated in proto" : null);
  }
  return builder.build();
}
 
Example #24
Source File: SchemaToProto.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
private static String toType(GraphQLType type) {
  if (type instanceof GraphQLList) {
    return "repeated " + toType(((GraphQLList) type).getWrappedType());
  } else if (type instanceof GraphQLObjectType) {
    return ((GraphQLObjectType) type).getName();
  } else if (type instanceof GraphQLEnumType) {
    return ((GraphQLEnumType) type).getName() + ".Enum";
  } else {
    return TYPE_MAP.get(((GraphQLNamedType) type).getName());
  }
}
 
Example #25
Source File: WrappingTypeGenerator.java    From graphql-java-type-generator with MIT License 4 votes vote down vote up
@Override
protected GraphQLEnumType generateEnumType(Object object) {
    return getNextGen().generateEnumType(object);
}
 
Example #26
Source File: EnumMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public GraphQLEnumType toGraphQLInputType(String typeName, AnnotatedType javaType, TypeMappingEnvironment env) {
    return toGraphQLType(typeName, javaType, env);
}
 
Example #27
Source File: ProtoToGqlTest.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
@Test
public void checkComments() {

  String DEFAULT_DESCRIPTOR_SET_FILE_LOCATION = "META-INF/proto/descriptor_set.desc";

  ImmutableMap<String, String> comments =
      DescriptorSet.getCommentsFromDescriptorFile(
          DescriptorSet.class
              .getClassLoader()
              .getResourceAsStream(DEFAULT_DESCRIPTOR_SET_FILE_LOCATION));

  SchemaOptions.Builder schemaOptionsBuilder = SchemaOptions.builder();
  schemaOptionsBuilder.commentsMapBuilder().putAll(comments);
  GraphQLObjectType result =
      ProtoToGql.convert(Proto1.getDescriptor(), null, schemaOptionsBuilder.build());

  GraphQLFieldDefinition intFieldGraphQLFieldDefinition = result.getFieldDefinition("intField");
  assertThat(intFieldGraphQLFieldDefinition).isNotNull();
  assertThat(
          intFieldGraphQLFieldDefinition
              .getDescription()
              .equals("Some leading comment. Some trailing comment"))
      .isTrue();

  GraphQLFieldDefinition camelCaseNameGraphQLFieldDefinition =
      result.getFieldDefinition("camelCaseName");
  assertThat(camelCaseNameGraphQLFieldDefinition).isNotNull();
  assertThat(camelCaseNameGraphQLFieldDefinition.getDescription().equals("Some leading comment"))
      .isTrue();

  GraphQLFieldDefinition testProtoNameGraphQLFieldDefinition =
      result.getFieldDefinition("testProto");
  assertThat(testProtoNameGraphQLFieldDefinition).isNotNull();
  assertThat(testProtoNameGraphQLFieldDefinition.getDescription().equals("Some trailing comment"))
      .isTrue();

  GraphQLEnumType nestedEnumType = ProtoToGql.convert(TestEnum.getDescriptor(), schemaOptionsBuilder.build());

  GraphQLEnumValueDefinition graphQLFieldDefinition = nestedEnumType.getValue("UNKNOWN");
  assertThat(graphQLFieldDefinition.getDescription().equals("Some trailing comment")).isTrue();

  GraphQLObjectType nestedMessageType =
      ProtoToGql.convert(Proto2.NestedProto.getDescriptor(), null, schemaOptionsBuilder.build());

  assertThat(nestedMessageType.getDescription().equals("Nested type comment")).isTrue();

  GraphQLFieldDefinition nestedFieldGraphQLFieldDefinition =
      nestedMessageType.getFieldDefinition("nestedId");
  assertThat(nestedFieldGraphQLFieldDefinition).isNotNull();
  assertThat(nestedFieldGraphQLFieldDefinition.getDescription().equals("Some nested id"))
      .isTrue();

  GraphQLEnumType enumType =
      ProtoToGql.convert(TestProto.TestEnumWithComments.getDescriptor(), schemaOptionsBuilder.build());

  graphQLFieldDefinition = enumType.getValue("FOO");
  assertThat(graphQLFieldDefinition.getDescription().equals("Some trailing comment")).isTrue();
}
 
Example #28
Source File: SchemaToProtoTest.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
@Test
public void schemaWithEnumsShouldGenerateCorrectProto() {
  assertThat(
          SchemaToProto.toProto(
              GraphQLSchema.newSchema()
                  .query(
                      GraphQLObjectType.newObject()
                          .name("queryType")
                          .field(
                              GraphQLFieldDefinition.newFieldDefinition()
                                  .name("enum")
                                  .type(
                                      GraphQLEnumType.newEnum()
                                          .name("enumType")
                                          .value("a")
                                          .value("b")
                                          .value("c")
                                          .build())))
                  .build()))
      .isEqualTo(
          "// LINT: LEGACY_NAMES\n"
              + "// Autogenerated. Do not edit.\n"
              + "syntax = \"proto3\";\n"
              + "\n"
              + "package google.api.graphql.rejoiner.proto;\n"
              + "\n"
              + "option java_package = \"com.google.api.graphql.rejoiner.proto\";\n"
              + "option (jspb.js_namespace) = \"com.google.api.graphql.rejoiner.proto\";\n"
              + "import \"java/com/google/apps/jspb/jspb.proto\";\n"
              + "\n"
              + "message queryType {\n"
              + "option (jspb.message_id) = \"graphql.queryType\";\n"
              + "enumType.Enum enum = 1;\n"
              + "}\n"
              + "\n"
              + "message enumType {\n"
              + " option (jspb.message_id) = \"graphql.enumType\";\n"
              + " enum Enum {\n"
              + "a = 0;\n"
              + "b = 1;\n"
              + "c = 2;\n"
              + "}\n"
              + "}");
}
 
Example #29
Source File: TypeGenerator.java    From graphql-java-type-generator with MIT License votes vote down vote up
protected abstract GraphQLEnumType generateEnumType(Object object);