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.
Groovy
Kotlin
1apollo {
2 customTypeMapping = [
3 "Date" : "java.util.Date"
4 ]
5}
1apollo {
2 customTypeMapping.set(mapOf(
3 "Date" to "java.util.Date"
4 ))
5}
Next, register your custom adapter and add it to your ApolloClient
builder:
Kotlin
1val dateCustomTypeAdapter = object : CustomTypeAdapter<Date> {
2 override fun decode(value: CustomTypeValue<*>): Date {
3 return try {
4 DATE_FORMAT.parse(value.value.toString())
5 } catch (e: ParseException) {
6 throw RuntimeException(e)
7 }
8 }
9
10 override fun encode(value: Date): CustomTypeValue<*> {
11 return GraphQLString(DATE_FORMAT.format(value))
12 }
13}
14
15ApolloClient.builder()
16 .serverUrl(serverUrl)
17 .addCustomTypeAdapter(CustomType.DATE, dateCustomTypeAdapter)
18 .build()