/
Launch Apollo Studio

Custom scalar types


Apollo supports custom scalar types, such as Date.

You first need to define the mapping in your build.gradle file. This maps from the GraphQL type to the Java/Kotlin class to use in code.

apollo {
  customTypeMapping = [
    "Date" : "java.util.Date"
  ]
}

Next, register your custom adapter and add it to your ApolloClient builder:

val dateCustomTypeAdapter = object : CustomTypeAdapter<Date> {
  override fun decode(value: CustomTypeValue<*>): Date {
    return try {
      DATE_FORMAT.parse(value.value.toString())
    } catch (e: ParseException) {
      throw RuntimeException(e)
    }
  }

  override fun encode(value: Date): CustomTypeValue<*> {
    return GraphQLString(DATE_FORMAT.format(value))
  }
}

ApolloClient.builder()
  .serverUrl(serverUrl)
  .addCustomTypeAdapter(CustomType.DATE, dateCustomTypeAdapter)
  .build()
Edit on GitHub