GitHub APIで使用していたら、一部がAnyになってしまいました。
以下のようなファイルが生成されていました。
これを2つの工程で好きな型に変換します。
// 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.github.type import com.apollographql.apollo.api.ScalarType import kotlin.String enum class CustomType : ScalarType { DATETIME { override fun typeName(): String = "DateTime" override fun className(): String = "kotlin.Any" }, ID { override fun typeName(): String = "ID" override fun className(): String = "kotlin.String" }, URI { override fun typeName(): String = "URI" override fun className(): String = "kotlin.Any" } }
生成される型を変更する
build.gradle.ktsの customTypeMapping
に変換先の型を指定します。
apollo { generateKotlinModels.set(true) customTypeMapping.set( mapOf( "URI" to "java.net.URI", "DateTime" to "java.util.Calendar" ) ) }
変換方法を書いて指定する
変換方法を書く
internal object CustomTypeDataTimeAdapter : CustomTypeAdapter<Calendar> { private val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") override fun decode(value: CustomTypeValue<*>): Calendar { return Calendar.getInstance().also { it.timeInMillis = format .parse(value.value.toString()).time } } override fun encode(value: Calendar): CustomTypeValue<*> { return CustomTypeValue.fromRawValue(format.format(value.time)) } }
internal object CustomTypeURIAdapter: CustomTypeAdapter<URI> { override fun decode(value: CustomTypeValue<*>): URI { return URI(value.value.toString()) } override fun encode(value: URI): CustomTypeValue<*> { return CustomTypeValue.fromRawValue(value.toASCIIString()) } }
指定する
private val gitHubApolloClient = ApolloClient.builder() .addCustomTypeAdapter(CustomType.URI, CustomTypeURIAdapter) .addCustomTypeAdapter(CustomType.DATETIME, CustomTypeDataTimeAdapter)