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

commonMain.app.moviebase.trakt.core.HttpClientExtensions.kt Maven / Gradle / Ivy

There is a newer version: 0.6.0
Show newest version
package app.moviebase.trakt.core

import io.ktor.client.HttpClient
import io.ktor.client.call.HttpClientCall
import io.ktor.client.call.body
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.HttpRequestPipeline
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.statement.HttpResponsePipeline
import io.ktor.util.pipeline.PipelinePhase

internal suspend inline fun  HttpClient.getByPaths(
    vararg paths: String,
    block: HttpRequestBuilder.() -> Unit = {},
): T = get(urlString = buildPaths(*paths), block = block).body()

internal suspend inline fun  HttpClient.getByPaths(
    paths: Collection,
    block: HttpRequestBuilder.() -> Unit = {},
): T = get(urlString = buildPaths(paths), block = block).body()

internal suspend inline fun  HttpClient.postByPaths(
    vararg paths: String,
    block: HttpRequestBuilder.() -> Unit = {},
): T = post(urlString = buildPaths(*paths), block = block).body()

internal suspend inline fun  HttpClient.postByPaths(
    paths: Collection,
    block: HttpRequestBuilder.() -> Unit = {},
): T = post(urlString = buildPaths(paths), block = block).body()

internal suspend inline fun  HttpClient.deleteByPaths(
    vararg paths: String,
    block: HttpRequestBuilder.() -> Unit = {},
): T = delete(urlString = buildPaths(*paths), block = block).body()

internal suspend inline fun  HttpClient.deleteByPaths(
    paths: Collection,
    block: HttpRequestBuilder.() -> Unit = {},
): T = delete(urlString = buildPaths(paths), block = block).body()

private fun buildPaths(vararg paths: String): String = paths.joinToString(separator = "/")
private fun buildPaths(paths: Collection): String = paths.joinToString(separator = "/")

typealias RequestInterceptor = suspend (HttpRequestBuilder) -> Unit
typealias ResponseInterceptor = suspend (HttpClientCall) -> Unit

fun HttpClient.interceptRequest(phase: PipelinePhase = HttpRequestPipeline.Render, interceptor: RequestInterceptor) =
    requestPipeline.intercept(phase) { interceptor(context) }

/**
 * Interceptor for throwing an exception must run before [HttpResponsePipeline.Transform] phase.
 */
fun HttpClient.interceptResponse(phase: PipelinePhase = HttpResponsePipeline.Parse, interceptor: ResponseInterceptor) =
    responsePipeline.intercept(phase) { interceptor(context) }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy