Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/commonMain/kotlin/co/pokeapi/pokekotlin/PokeApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,7 @@ public fun PokeApi(
configure()
install(HttpCache) { cacheStorage?.let { privateStorage(it) } }
install(ContentNegotiation) { json(PokeApiJson, ContentType.Any) }
expectSuccess = true
}
)
.converterFactories(ResultConverter.Factory)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,21 @@ import de.jensklingenberg.ktorfit.converter.Converter
import de.jensklingenberg.ktorfit.converter.KtorfitResult
import de.jensklingenberg.ktorfit.converter.TypeData
import io.ktor.client.call.body
import io.ktor.client.plugins.ClientRequestException
import io.ktor.client.plugins.RedirectResponseException
import io.ktor.client.plugins.ResponseException
import io.ktor.client.plugins.ServerResponseException
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText
import io.ktor.http.isSuccess

internal class ResultConverter(private val typeData: TypeData) :
Converter.SuspendResponseConverter<HttpResponse, Result<Any>> {

private suspend fun HttpResponse.toException(): Throwable {
val exceptionResponseText = runCatching { bodyAsText() }.getOrElse { "<body failed decoding>" }
return when (status.value) {
in 300..399 -> RedirectResponseException(this, exceptionResponseText)
in 400..499 -> ClientRequestException(this, exceptionResponseText)
in 500..599 -> ServerResponseException(this, exceptionResponseText)
else -> ResponseException(this, exceptionResponseText)
}
}

override suspend fun convert(result: KtorfitResult): Result<Any> {
return when (result) {
is KtorfitResult.Failure -> Result.failure(result.throwable)
is KtorfitResult.Success -> {
when {
result.response.status.isSuccess() ->
Result.success(result.response.body(typeData.typeArgs.first().typeInfo))
else -> Result.failure(result.response.toException())
// we configure the client with expectSuccess
else -> error("impossible: " + result.response)
}
}
}
Expand Down
Loading