0

With ktor client, I've got a non-serializable object derived from a serializable object like so:

@Serializable
@SerialName("login-request")
open class LoginRequest (
    open val email : String = "",
    open val password : String = ""
) : ServiceRequestPayload

impl class

class LoginRequestVo : LoginRequest("", ""), NodeComponent by NodeComponentImpl() {
    override val email: String by subject("")
    override val password: String by subject("")
}

Now when I manually use kotlinx serialization on this like so:

val request : LoginRequest = LoginRequestVo().apply {
    email = "test@gmail.com"
    password = "password"
}

val str = Json.encodeToString(request)
println(str)

It correctly serializes it, and when deserialized on the other side, it correctly deserializes to LoginRequest. However, when I use ktor-client to serialize my object, it complains that LoginRequestVo is not serializable. The example code below uses some other objects from my project and has more information that you need, but the gist is that the type of U in the invoke function and therefore the request.payload expression is type LoginRequest as specified by the LoginServiceImpl below.

suspend inline fun <T, U: ServiceRequestPayload> HttpClient.invoke(desc : EndpointDescriptor<T, U>, request : ServiceRequest<U>? ) : ServiceResponse {
    val path = "/api${desc.path}"
    return when(desc.method) {
        HttpMethod.GET -> {
            get(path)
        }
        HttpMethod.POST -> {
            if (request == null) {
                post(path)
            } else {
                post(path) {
                    contentType(ContentType.Application.Json)
                    body = request.payload
                }
            }
        }
        HttpMethod.DELETE -> delete(desc.path)
        HttpMethod.PUT -> {
            if (request == null) {
                put(path)
            } else {
                post(path) {
                    contentType(ContentType.Application.Json)
                    body = request.payload
                }
            }
        }
    }
}

class LoginServiceImpl(
    context : ApplicationContext
) : LoginService {
    private val client by context.service<HttpClient>()

    override suspend fun login(request: ServiceRequest<LoginRequest>) = client.invoke(LoginServiceDesc.login, request)
    override suspend fun register(request: ServiceRequest<LoginRequest>) = client.invoke(LoginServiceDesc.register, request)
}

The error I get is: enter image description here

My question is, Is there a way to specify to ktor-client the type or the serializer to use when it needs to serialize a body?

FatalCatharsis
  • 3,407
  • 5
  • 44
  • 74

0 Answers0