org.openapitools.client.infrastructure.HttpResponse.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlin-client-petstore-multiplatform
Show all versions of kotlin-client-petstore-multiplatform
A demo for deployment to the Central Repository. A kotlin client library for OpenAPI Petstore by org.openapitools
The newest version!
package org.openapitools.client.infrastructure
import io.ktor.client.call.TypeInfo
import io.ktor.client.call.typeInfo
import io.ktor.http.Headers
import io.ktor.http.isSuccess
open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) {
val status: Int = response.status.value
val success: Boolean = response.status.isSuccess()
val headers: Map> = response.headers.mapEntries()
suspend fun body(): T = provider.body(response)
suspend fun typedBody(type: TypeInfo): V = provider.typedBody(response, type)
companion object {
private fun Headers.mapEntries(): Map> {
val result = mutableMapOf>()
entries().forEach { result[it.key] = it.value }
return result
}
}
}
interface BodyProvider {
suspend fun body(response: io.ktor.client.statement.HttpResponse): T
suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V
}
class TypedBodyProvider(private val type: TypeInfo) : BodyProvider {
@Suppress("UNCHECKED_CAST")
override suspend fun body(response: io.ktor.client.statement.HttpResponse): T =
response.call.receive(type) as T
@Suppress("UNCHECKED_CAST")
override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V =
response.call.receive(type) as V
}
class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider {
override suspend fun body(response: io.ktor.client.statement.HttpResponse): T =
block(provider.body(response))
override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V =
provider.typedBody(response, type)
}
inline fun io.ktor.client.statement.HttpResponse.wrap(): HttpResponse =
HttpResponse(this, TypedBodyProvider(typeInfo()))
fun HttpResponse.map(block: T.() -> V): HttpResponse =
HttpResponse(response, MappedBodyProvider(provider, block))