```suspend fun GETRequest( baseUrl:String, ...
# ktor
d
Copy code
suspend fun GETRequest(
    baseUrl:String,
    path: String,
    headers: List<Headers>? = null,
    model: , MODEL_CLASS_NAME
    json: Json = Json {
        ignoreUnknownKeys = true
    }
) : MODEL_CLASS {
    val builder = HttpRequestBuilder()
    builder.method = HttpMethod.Get
    builder.url {
        takeFrom(baseUrl)
        encodedPath = encodedPath.let { startingPath ->
            path(path)
            return@let startingPath + encodedPath.substring(1)
        }
    }

    with(builder.headers) {
        if (!headers.isNullOrEmpty()) {
            headers.forEach {
                append(it.key, it.value)
            }
        }
    }

    try {
        val serializer = model.serializer()

        //not primitive type
        val result: String = httpApiClient.request(builder)
        return json.decodeFromString(serializer, result)
    } catch (pipeline: ReceivePipelineException) {
        throw pipeline.cause
    }
}
I am trying to make a generic GETrequest function which can be used from Android and iOS in Ktor native with KMM, I am not sure how can we pass the
MODEL_CLASS_NAME
, any idea ?
a
You can use the expect/actual feature to define expectations in the common code and to write their implementations for each platform.
d
Sorry, I mean in the current function I want to make the
model
parameter to a class which is serializable as I am using the
.serializer
in this class
Its a generic function which we can use to send any POJO model to the API and get a response in that type of model parsed
ex, I make call to CovidCountry API, the return model is
Copy code
{
  "country": "US",
  "affected": 1000,
  "date": "today"
}
I make a model as
Copy code
@Serializable
data class CountryCovid(val country:String,val affected:Int, val date:String)
I can use the current function as
Copy code
val data = APiClient.GETRequest("https:://covidCountryApi.com/","/usdata.json", CountryCovid::class)
now here I get the
data
as the
CountryCovid
class.
a
Can you just have a parameter with the KClass type? Maybe, I don't understand something.
d
@Aleksei Tirman [JB] yes, I tried with
KClass<*>
but the issue with this is, we can pass any class, whereas the function should allow only classes with
@Serializable
annotation, also sometimes we want to get a List in return as
List<CountryCovid>
a
I guess you could only check that class is serializable in runtime.
By running
serializerOrNull