commonMain.de.jensklingenberg.ktorfit.Response.kt Maven / Gradle / Ivy
package de.jensklingenberg.ktorfit
import io.ktor.client.statement.HttpResponse
import io.ktor.http.Headers
import io.ktor.http.HttpStatusCode
import io.ktor.http.isSuccess
/** An HTTP response. */
@Suppress("MemberVisibilityCanBePrivate")
public class Response private constructor(
private val rawResponse: HttpResponse,
private val body: T?,
private val errorBody: Any?,
) {
/** The raw response from the HTTP client. */
public fun raw(): HttpResponse = rawResponse
/** HTTP status. */
public val status: HttpStatusCode get() = rawResponse.status
/** HTTP status code. */
public val code: Int
get() = status.value
/** HTTP status message or null if unknown. */
public val message: String
get() = status.toString()
/** HTTP headers. */
public val headers: Headers
get() = rawResponse.headers
/** Returns true if status code is in the range [200..300). */
public val isSuccessful: Boolean
get() = status.isSuccess()
/** The deserialized response body of a [isSuccessful] response. */
public fun body(): T? = body
/** The raw response body of an [unsuccessful] response. */
public fun errorBody(): Any? = errorBody
override fun toString(): String = rawResponse.toString()
public companion object {
/**
* Create a successful response from `rawResponse` with `body` as the deserialized
* body.
*/
public fun success(
body: T?,
rawResponse: HttpResponse,
): Response {
require(rawResponse.status.isSuccess()) { "rawResponse must be successful response" }
return Response(rawResponse, body, null)
}
/** Create an error response from `rawResponse` with `body` as the error body. */
public fun error(
body: Any,
rawResponse: HttpResponse,
): Response {
require(!rawResponse.status.isSuccess()) { "rawResponse should not be successful response" }
return Response(rawResponse, null, body)
}
}
}