divyanshunegi
07/02/2021, 5:14 AMsuspend 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 ?Aleksei Tirman [JB]
07/02/2021, 10:42 AMdivyanshunegi
07/02/2021, 11:20 AMmodel
parameter to a class which is serializable as I am using the .serializer
in this classdivyanshunegi
07/02/2021, 11:21 AMdivyanshunegi
07/02/2021, 11:24 AM{
"country": "US",
"affected": 1000,
"date": "today"
}
I make a model as
@Serializable
data class CountryCovid(val country:String,val affected:Int, val date:String)
I can use the current function as
val data = APiClient.GETRequest("https:://covidCountryApi.com/","/usdata.json", CountryCovid::class)
now here I get the data
as the CountryCovid
class.Aleksei Tirman [JB]
07/02/2021, 11:37 AMdivyanshunegi
07/02/2021, 11:49 AMKClass<*>
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>
Aleksei Tirman [JB]
07/02/2021, 12:36 PMAleksei Tirman [JB]
07/02/2021, 12:36 PMserializerOrNull