Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using field's Json name instead of internal conversion from snake cas… #54

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,6 @@ final class GqlInputConverter {
private final BiMap<String, Descriptor> descriptorMapping;
private final BiMap<String, EnumDescriptor> enumMapping;

private static final Converter<String, String> UNDERSCORE_TO_CAMEL =
CaseFormat.LOWER_UNDERSCORE.converterTo(CaseFormat.LOWER_CAMEL);

private GqlInputConverter(
BiMap<String, Descriptor> descriptorMapping, BiMap<String, EnumDescriptor> enumMapping) {
this.descriptorMapping = descriptorMapping;
Expand All @@ -72,7 +69,7 @@ Message createProtoBuf(

Map<String, Object> remainingInput = new HashMap<>(input);
for (FieldDescriptor field : descriptor.getFields()) {
String fieldName = getFieldName(field);
String fieldName = field.getJsonName();

if (!remainingInput.containsKey(fieldName)) {
// TODO: validate required fields
Expand Down Expand Up @@ -107,7 +104,7 @@ GraphQLType getInputType(Descriptor descriptor) {
for (FieldDescriptor field : descriptor.getFields()) {
GraphQLType fieldType = getFieldType(field);
GraphQLInputObjectField.Builder inputBuilder =
GraphQLInputObjectField.newInputObjectField().name(getFieldName(field));
GraphQLInputObjectField.newInputObjectField().name(field.getJsonName());
if (field.isRepeated()) {
inputBuilder.type(new GraphQLList(fieldType));
} else {
Expand Down Expand Up @@ -145,12 +142,6 @@ static String getReferenceName(GenericDescriptor descriptor) {
return "Input_" + ProtoToGql.getReferenceName(descriptor);
}

/** Field names with under_scores are converted to camelCase. */
private String getFieldName(FieldDescriptor field) {
String fieldName = field.getName();
return fieldName.contains("_") ? UNDERSCORE_TO_CAMEL.convert(fieldName) : fieldName;
}

private GraphQLType getFieldType(FieldDescriptor field) {
if (field.getType() == FieldDescriptor.Type.MESSAGE
|| field.getType() == FieldDescriptor.Type.GROUP) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,6 @@

package com.google.api.graphql.rejoiner;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static graphql.Scalars.GraphQLID;
import static graphql.Scalars.GraphQLString;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;

import com.google.api.graphql.options.RelayOptionsProto;
import com.google.common.base.CaseFormat;
import com.google.common.base.CharMatcher;
Expand All @@ -33,6 +28,12 @@
import com.google.protobuf.Descriptors.FieldDescriptor.Type;
import com.google.protobuf.Descriptors.GenericDescriptor;
import com.google.protobuf.Message;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Optional;

import graphql.Scalars;
import graphql.relay.Relay;
import graphql.schema.DataFetcher;
Expand All @@ -47,10 +48,11 @@
import graphql.schema.GraphQLScalarType;
import graphql.schema.GraphQLType;
import graphql.schema.GraphQLTypeReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Optional;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static graphql.Scalars.GraphQLID;
import static graphql.Scalars.GraphQLString;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;

/** Converts Protos to GraphQL Types. */
final class ProtoToGql {
Expand All @@ -77,10 +79,10 @@ private ProtoToGql() {}
.put(Type.SFIXED64, Scalars.GraphQLLong)
.build();

private static final Converter<String, String> UNDERSCORE_TO_CAMEL =
CaseFormat.LOWER_UNDERSCORE.converterTo(CaseFormat.LOWER_CAMEL);
private static final Converter<String, String> LOWER_CAMEL_TO_UPPER =
CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL);
private static final Converter<String, String> UNDERSCORE_TO_CAMEL =
CaseFormat.LOWER_UNDERSCORE.converterTo(CaseFormat.LOWER_CAMEL);
private static final FieldConverter FIELD_CONVERTER = new FieldConverter();
private static final ImmutableList<GraphQLFieldDefinition> STATIC_FIELD =
ImmutableList.of(newFieldDefinition().type(GraphQLString).name("_").staticValue("-").build());
Expand Down Expand Up @@ -110,53 +112,53 @@ public Object get(DataFetchingEnvironment environment) {
}
if (type instanceof GraphQLList) {

Object listValue = call(source, "get" + LOWER_CAMEL_TO_UPPER.convert(name) + "List");
Object listValue = call(source, "get" + name + "List");
if (listValue != null) {
return listValue;
}
Object mapValue = call(source, "get" + LOWER_CAMEL_TO_UPPER.convert(name) + "Map");
Object mapValue = call(source, "get" + name + "Map");
if (mapValue == null) {
return null;
}
Map<?, ?> map = (Map<?, ?>) mapValue;
return map.entrySet().stream().map(entry -> ImmutableMap.of("key", entry.getKey(), "value", entry.getValue())).collect(toImmutableList());
return map.entrySet().stream().map(entry -> ImmutableMap.of("key", entry.getKey(),
"value", entry.getValue())).collect(toImmutableList());
}
if (type instanceof GraphQLEnumType) {
Object o = call(source, "get" + LOWER_CAMEL_TO_UPPER.convert(name));
Object o = call(source, "get" + name);
if (o != null) {
return o.toString();
}
}

return call(source, "get" + LOWER_CAMEL_TO_UPPER.convert(name));
return call(source, "get" + name);
}

private static Object call(Object object, String methodName) {
try {
Method method = object.getClass().getMethod(methodName);
return method.invoke(object);
} catch (NoSuchMethodException e) {
return null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}

@Override
public GraphQLFieldDefinition apply(FieldDescriptor fieldDescriptor) {
String fieldName = fieldDescriptor.getName();
String convertedFieldName = fieldName.contains("_") ? UNDERSCORE_TO_CAMEL.convert(fieldName) : fieldName;
GraphQLFieldDefinition.Builder builder =
GraphQLFieldDefinition.newFieldDefinition()
.type(convertType(fieldDescriptor))
.dataFetcher(
new ProtoDataFetcher(convertedFieldName))
.name(convertedFieldName);
if (fieldDescriptor.getFile().toProto().getSourceCodeInfo().getLocationCount()
> fieldDescriptor.getIndex()) {
new ProtoDataFetcher(
LOWER_CAMEL_TO_UPPER.convert(
UNDERSCORE_TO_CAMEL.convert(fieldDescriptor.getName())
)
)
)
.name(fieldDescriptor.getJsonName());
if (fieldDescriptor.getFile().toProto().
getSourceCodeInfo().getLocationCount() > fieldDescriptor.getIndex()) {
builder.description(
fieldDescriptor
.getFile()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,22 @@

import com.google.api.graphql.rejoiner.TestProto.Proto1;
import com.google.api.graphql.rejoiner.TestProto.Proto2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.truth.Truth;
import com.google.common.truth.extensions.proto.ProtoTruth;
import com.google.protobuf.Message;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLInputObjectType;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link com.google.api.graphql.rejoiner.GqlInputConverter}. */
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLInputObjectType;

/**
* Unit tests for {@link com.google.api.graphql.rejoiner.GqlInputConverter}.
*/
@RunWith(JUnit4.class)
public final class GqlInputConverterTest {

Expand All @@ -45,16 +50,33 @@ public void inputConverterShouldFillProtoBuf() {
Proto1.getDescriptor(),
Proto1.newBuilder(),
ImmutableMap.of(
"id", "id", "intField", 123, "testProto", ImmutableMap.of("innerId", "1")));
"id", "id", "intField", 123, "testProto",
ImmutableMap.of("innerId", "1", "enums", ImmutableList.of(Proto2.TestEnum.FOO, Proto2.TestEnum.BAR))
, "RenamedField", "someName"));
ProtoTruth.assertThat(protoBuf)
.isEqualTo(
Proto1.newBuilder()
.setId("id")
.setIntField(123)
.setTestProto(Proto2.newBuilder().setInnerId("1").build())
.setTestProto(Proto2.newBuilder().setInnerId("1")
.addEnums(Proto2.TestEnum.FOO)
.addEnums(Proto2.TestEnum.BAR)
.build())
.setNameField("someName")
.build());
}

@Test(expected = AssertionError.class)
public void inputConverterShouldFillProtoBufAllFields() {
GqlInputConverter inputConverter =
GqlInputConverter.newBuilder().add(TestProto.getDescriptor().getFile()).build();
inputConverter.createProtoBuf(
Proto1.getDescriptor(),
Proto1.newBuilder(),
ImmutableMap.of(
"id", "id", "intField", 123, "test_proto", ImmutableMap.of("innerId", "1")));
}

@Test
public void inputConverterShouldCreateArgument() {
GqlInputConverter inputConverter =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public void convertShouldWorkForMessage() {
GraphQLObjectType result = ProtoToGql.convert(Proto1.getDescriptor(), null);
assertThat(result.getName())
.isEqualTo("javatests_com_google_api_graphql_rejoiner_proto_Proto1");
assertThat(result.getFieldDefinitions()).hasSize(5);
assertThat(result.getFieldDefinitions()).hasSize(6);
}

@Test
Expand All @@ -73,7 +73,7 @@ public void convertShouldWorkForEnums() {
@Test
public void checkFieldNameCamelCase() {
GraphQLObjectType result = ProtoToGql.convert(Proto1.getDescriptor(), null);
assertThat(result.getFieldDefinitions()).hasSize(5);
assertThat(result.getFieldDefinitions()).hasSize(6);
assertThat(result.getFieldDefinition("intField")).isNotNull();
assertThat(result.getFieldDefinition("camelCaseName")).isNotNull();
}
Expand Down
1 change: 1 addition & 0 deletions rejoiner/src/test/proto/test_proto.proto
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ message Proto1 {
Proto2 test_proto = 3;
InnerProto test_inner_proto = 4;
int64 camelCaseName = 5;
string name_field = 6 [json_name="RenamedField"];

message InnerProto {
string foo = 1;
Expand Down