MR3Y
09/17/2023, 10:24 PMkotlinx @Serializable responses in sealed classes for modeling Success & Error respectively:
val result: ApiResult<List<Foo>> = client.get(url).body()
when(result) {
is ApiResult.Success -> {}
is ApiResult.Error -> {}
}
I made a ktor plugin to transform the response to my defined ApiResult sealed interface like this:
val plugin = createClientPlugin("ApiResultWrapper") {
transformResponseBody { response, _, _ ->
if (response.status.isSuccess()) {
try {
ApiResult.Success(response.body())
} catch (e: Exception) {
ApiResult.Error(code = null, throwable = e)
}
} else {
ApiResult.Error(code = response.status.value, throwable = null)
}
}
}
but, Apparently, response.body() returns HttpResponse[/*request url*/, 200 OK] instead of deserializing the actual payload of the response. I've been following the docs, some samples, and also did some searching here in the channel but couldn't find how to solve my problem or which API exactly I need to use? Thanks in advance.Aleksei Tirman [JB]
09/18/2023, 5:18 AMApiResult class?MR3Y
09/18/2023, 11:03 AMsealed interface ApiResult<out T : Any> {
data class Success<out T : Any>(val data: T) : ApiResult<T>
data class Error(val code: Int?, val throwable: Throwable? = null) : ApiResult<Nothing>
}MR3Y
09/18/2023, 10:48 PMKSerializer from typeInfo . I tried this:
jsonInstance.decodeFromString(typeInfo.ofInnerClassParameter().type.serializer(), response.bodyAsText())
where ofInnerClassParameter() is:
fun TypeInfo.ofInnerClassParameter(): TypeInfo {
val typeProjection = kotlinType?.arguments?.get(0)
val kType = typeProjection!!.type!!
return TypeInfo(kType.classifier as KClass<*>, kType.platformType)
}
but I'm getting:
kotlinx.serialization.json.internal.JsonDecodingException: Expected class kotlinx.serialization.json.JsonObject as the serialized body of kotlinx.serialization.Polymorphic<List>, but had class kotlinx.serialization.json.JsonArray):
I guess I can't do this in an easy way due to type erasure on JVM.Aleksei Tirman [JB]
09/20/2023, 5:46 AM