Use DateTime scalar in GraphQL queries and mutation on Android

Viewed 922

I'm working with GraphQL. The schema contains:

scalar DateTime
type Something {
    timestamp: DateTime
}

When I build the app the ApolloClient plugin generates the class:

public class DateTime {
  public companion object {
    public val type: CustomScalarType = CustomScalarType("DateTime", "kotlin.Any")
  }
}

Do I have to use this one when I build the ApolloClient? Like this?

val apolloClient = ApolloClient.builder()
    .serverUrl("xxxx")
    .okHttpClient(httpClient)
    .addCustomTypeAdapter(DateTime.type, adapter)
    .build()

I found here the list of the already available adapters but I can't find how to import them and anyway none of them seems appropriate.

Do I have to define my own custom adapter?

EDIT To import them it is enough to import com.apollographql.apollo3:apollo-adapters.

1 Answers

I found the solution. There are three steps.

Import/create adapter

You can either import the library from apollo:

implementation "com.apollographql.apollo3:apollo-adapters:${apollo_version}"

and then use the DateAdapter or create the adapter by yourself maybe following the way DateAdapter does it:


/**
 * An [Adapter] that converts an ISO 8601 String like "2010-06-01T22:19:44.475Z" to/from
 * a java [Date]
 *
 * It requires Android Gradle plugin 4.0 or newer and [core library desugaring](https://developer.android.com/studio/write/java8-support#library-desugaring).
 */
object DateAdapter : Adapter<Date> {
  override fun fromJson(reader: JsonReader, customScalarAdapters: CustomScalarAdapters): Date {
    return Date(Instant.parse(reader.nextString()!!).toEpochMilliseconds())
  }

  override fun toJson(writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: Date) {
    writer.value(Instant.fromEpochMilliseconds(value.time).toString())
  }
}

Use the adapter:

val apolloClient = ApolloClient.builder()
    .serverUrl("xxxx")
    .okHttpClient(httpClient)
    .addCustomTypeAdapter(DateTime.type, DateAdapter())
    .build()

Update build.gradle

In the build.gradle update the section for apollo:

apollo {
    customTypeMapping['DateTime'] = "java.util.Date"
}
Related