All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kotlin-client.libraries.jvm-ktor.infrastructure.HttpResponse.kt.mustache Maven / Gradle / Ivy

There is a newer version: 7.6.0
Show newest version
package {{packageName}}.infrastructure

import io.ktor.http.Headers
import io.ktor.http.isSuccess
import io.ktor.util.reflect.TypeInfo
import io.ktor.util.reflect.typeInfo

{{#nonPublicApi}}internal {{/nonPublicApi}}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)

    {{#nonPublicApi}}internal {{/nonPublicApi}}companion object {
        private fun Headers.mapEntries(): Map> {
            val result = mutableMapOf>()
            entries().forEach { result[it.key] = it.value }
            return result
        }
    }
}

{{#nonPublicApi}}internal {{/nonPublicApi}}interface BodyProvider {
    suspend fun body(response: io.ktor.client.statement.HttpResponse): T
    suspend fun  typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V
}

{{#nonPublicApi}}internal {{/nonPublicApi}}class TypedBodyProvider(private val type: TypeInfo) : BodyProvider {
    @Suppress("UNCHECKED_CAST")
    override suspend fun body(response: io.ktor.client.statement.HttpResponse): T =
            response.call.body(type) as T

    @Suppress("UNCHECKED_CAST")
    override suspend fun  typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V =
            response.call.body(type) as V
}

{{#nonPublicApi}}internal {{/nonPublicApi}}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)
}

{{#nonPublicApi}}internal {{/nonPublicApi}}inline fun  io.ktor.client.statement.HttpResponse.wrap(): HttpResponse =
        HttpResponse(this, TypedBodyProvider(typeInfo()))

{{#nonPublicApi}}internal {{/nonPublicApi}}fun  HttpResponse.map(block: T.() -> V): HttpResponse =
        HttpResponse(response, MappedBodyProvider(provider, block))