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

Workaround wrong input field default values #3398

Merged
merged 3 commits into from
Oct 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,28 @@ class InputTypeSpecBuilder(
)
}

private fun Any?.isEmptyList(): Boolean {
return if (this is List<*>) {
if (isEmpty()) {
true
} else {
first()?.isEmptyList() == true
}
} else {
false
}
}
private fun TypeSpec.Builder.addBuilder(): TypeSpec.Builder {
if (fields.isEmpty()) {
return this
} else {
val builderFields = fields.map { it.name.decapitalize().escapeJavaReservedWord() to it.javaTypeName(context) }
val builderFieldDefaultValues = fields
.filterNot {
// ignore any custom type default values for now as we don't support them
.filter {
// ignore any custom type or object default values for now as we don't support them
val normalizedType = it.type.removeSuffix("!").removeSurrounding("[", "]").removeSuffix("!")
normalizedType.isCustomScalarType(context)
!normalizedType.isCustomScalarType(context)
&& (!normalizedType.isInputObject(context) || it.defaultValue.isEmptyList())
}
.associate { it.name.decapitalize().escapeJavaReservedWord() to it.defaultValue }
val javaDocs = fields
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,37 @@ private val InputType.primaryConstructorSpec: FunSpec
.build()
}

private fun FieldType.leafType(): FieldType {
return when (this) {
is FieldType.Array -> this.rawType
else -> this
}
}

private fun Any?.isEmptyList(): Boolean {
return if (this is List<*>) {
if (isEmpty()) {
true
} else {
first()?.isEmptyList() == true
}
} else {
false
}
}

private fun InputType.Field.parameterSpec(): ParameterSpec {
val rawTypeName = type.asTypeName()
val typeName = when {
isOptional -> Input::class.asClassName().parameterizedBy(rawTypeName)
else -> rawTypeName
}
val defaultValue = defaultValue
/**
* For input objects, do not try to create a defaultValue
* See https://github.com/apollographql/apollo-android/issues/3394
*/
?.takeIf { type.leafType() !is FieldType.Object || it.isEmptyList() }
?.toDefaultValueCodeBlock(typeName = rawTypeName, fieldType = type)
.let { code ->
if (isOptional) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.apollographql.apollo.compiler

import com.apollographql.apollo.compiler.ast.ObjectType
import com.apollographql.apollo.compiler.ir.CodeGenerationContext
import com.apollographql.apollo.compiler.ir.TypeDeclaration.Companion.KIND_INPUT_OBJECT_TYPE
import com.apollographql.apollo.compiler.parser.introspection.IntrospectionSchema
import com.squareup.javapoet.*
import javax.lang.model.element.Modifier

Expand Down Expand Up @@ -415,6 +418,10 @@ fun String.isCustomScalarType(context: CodeGenerationContext): Boolean {
}
}

fun String.isInputObject(context: CodeGenerationContext): Boolean {
return context.typeDeclarations.firstOrNull { it.name == this }?.kind == KIND_INPUT_OBJECT_TYPE
}

fun TypeName.isScalar(context: CodeGenerationContext) = (Util.SCALAR_TYPES.contains(this) || isEnum(context))

fun normalizeGraphQlType(type: String, recursive: Boolean = false): String {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
query TestQuery($input: Input!) {
field(input: $input)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,272 @@
// AUTO-GENERATED FILE. DO NOT MODIFY.
//
// This class was automatically generated by Apollo GraphQL plugin from the GraphQL queries it found.
// It should not be modified by hand.
//
package com.example.input_field_default_value;

import com.apollographql.apollo.api.Operation;
import com.apollographql.apollo.api.OperationName;
import com.apollographql.apollo.api.Query;
import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.api.ResponseField;
import com.apollographql.apollo.api.ScalarTypeAdapters;
import com.apollographql.apollo.api.internal.InputFieldMarshaller;
import com.apollographql.apollo.api.internal.InputFieldWriter;
import com.apollographql.apollo.api.internal.OperationRequestBodyComposer;
import com.apollographql.apollo.api.internal.Optional;
import com.apollographql.apollo.api.internal.QueryDocumentMinifier;
import com.apollographql.apollo.api.internal.ResponseFieldMapper;
import com.apollographql.apollo.api.internal.ResponseFieldMarshaller;
import com.apollographql.apollo.api.internal.ResponseReader;
import com.apollographql.apollo.api.internal.ResponseWriter;
import com.apollographql.apollo.api.internal.SimpleOperationResponseParser;
import com.apollographql.apollo.api.internal.UnmodifiableMapBuilder;
import com.apollographql.apollo.api.internal.Utils;
import com.example.input_field_default_value.type.Input;
import java.io.IOException;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import okio.Buffer;
import okio.BufferedSource;
import okio.ByteString;
import org.jetbrains.annotations.NotNull;

public final class TestQuery implements Query<TestQuery.Data, Optional<TestQuery.Data>, TestQuery.Variables> {
public static final String OPERATION_ID = "e932e2ab855254eba685491d4fd87a8a0ddaadc3d02a6d7d0b7f5c341b0cdc43";

public static final String QUERY_DOCUMENT = QueryDocumentMinifier.minify(
"query TestQuery($input: Input!) {\n"
+ " field(input: $input)\n"
+ "}"
);

public static final OperationName OPERATION_NAME = new OperationName() {
@Override
public String name() {
return "TestQuery";
}
};

private final TestQuery.Variables variables;

public TestQuery(@NotNull Input input) {
Utils.checkNotNull(input, "input == null");
variables = new TestQuery.Variables(input);
}

@Override
public String operationId() {
return OPERATION_ID;
}

@Override
public String queryDocument() {
return QUERY_DOCUMENT;
}

@Override
public Optional<TestQuery.Data> wrapData(TestQuery.Data data) {
return Optional.fromNullable(data);
}

@Override
public TestQuery.Variables variables() {
return variables;
}

@Override
public ResponseFieldMapper<TestQuery.Data> responseFieldMapper() {
return new Data.Mapper();
}

public static Builder builder() {
return new Builder();
}

@Override
public OperationName name() {
return OPERATION_NAME;
}

@Override
@NotNull
public Response<Optional<TestQuery.Data>> parse(@NotNull final BufferedSource source,
@NotNull final ScalarTypeAdapters scalarTypeAdapters) throws IOException {
return SimpleOperationResponseParser.parse(source, this, scalarTypeAdapters);
}

@Override
@NotNull
public Response<Optional<TestQuery.Data>> parse(@NotNull final ByteString byteString,
@NotNull final ScalarTypeAdapters scalarTypeAdapters) throws IOException {
return parse(new Buffer().write(byteString), scalarTypeAdapters);
}

@Override
@NotNull
public Response<Optional<TestQuery.Data>> parse(@NotNull final BufferedSource source) throws
IOException {
return parse(source, ScalarTypeAdapters.DEFAULT);
}

@Override
@NotNull
public Response<Optional<TestQuery.Data>> parse(@NotNull final ByteString byteString) throws
IOException {
return parse(byteString, ScalarTypeAdapters.DEFAULT);
}

@Override
@NotNull
public ByteString composeRequestBody(@NotNull final ScalarTypeAdapters scalarTypeAdapters) {
return OperationRequestBodyComposer.compose(this, false, true, scalarTypeAdapters);
}

@NotNull
@Override
public ByteString composeRequestBody() {
return OperationRequestBodyComposer.compose(this, false, true, ScalarTypeAdapters.DEFAULT);
}

@Override
@NotNull
public ByteString composeRequestBody(final boolean autoPersistQueries,
final boolean withQueryDocument, @NotNull final ScalarTypeAdapters scalarTypeAdapters) {
return OperationRequestBodyComposer.compose(this, autoPersistQueries, withQueryDocument, scalarTypeAdapters);
}

public static final class Builder {
private @NotNull Input input;

Builder() {
}

public Builder input(@NotNull Input input) {
this.input = input;
return this;
}

public TestQuery build() {
Utils.checkNotNull(input, "input == null");
return new TestQuery(input);
}
}

public static final class Variables extends Operation.Variables {
private final @NotNull Input input;

private final transient Map<String, Object> valueMap = new LinkedHashMap<>();

Variables(@NotNull Input input) {
this.input = input;
this.valueMap.put("input", input);
}

public @NotNull Input input() {
return input;
}

@Override
public Map<String, Object> valueMap() {
return Collections.unmodifiableMap(valueMap);
}

@Override
public InputFieldMarshaller marshaller() {
return new InputFieldMarshaller() {
@Override
public void marshal(InputFieldWriter writer) throws IOException {
writer.writeObject("input", input.marshaller());
}
};
}
}

/**
* Data from the response after executing this GraphQL operation
*/
public static class Data implements Operation.Data {
static final ResponseField[] $responseFields = {
ResponseField.forInt("field", "field", new UnmodifiableMapBuilder<String, Object>(1)
.put("input", new UnmodifiableMapBuilder<String, Object>(2)
.put("kind", "Variable")
.put("variableName", "input")
.build())
.build(), false, Collections.<ResponseField.Condition>emptyList())
};

final int field;

private transient volatile String $toString;

private transient volatile int $hashCode;

private transient volatile boolean $hashCodeMemoized;

public Data(int field) {
this.field = field;
}

public int field() {
return this.field;
}

@SuppressWarnings({"rawtypes", "unchecked"})
public ResponseFieldMarshaller marshaller() {
return new ResponseFieldMarshaller() {
@Override
public void marshal(ResponseWriter writer) {
writer.writeInt($responseFields[0], field);
}
};
}

@Override
public String toString() {
if ($toString == null) {
$toString = "Data{"
+ "field=" + field
+ "}";
}
return $toString;
}

@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof Data) {
Data that = (Data) o;
return this.field == that.field;
}
return false;
}

@Override
public int hashCode() {
if (!$hashCodeMemoized) {
int h = 1;
h *= 1000003;
h ^= field;
$hashCode = h;
$hashCodeMemoized = true;
}
return $hashCode;
}

public static final class Mapper implements ResponseFieldMapper<Data> {
@Override
public Data map(ResponseReader reader) {
final int field = reader.readInt($responseFields[0]);
return new Data(field);
}
}
}
}
Loading