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

commonMain.in.shabinder.soundbound.zipline.HttpClient.kt Maven / Gradle / Ivy

package `in`.shabinder.soundbound.zipline

import app.cash.zipline.ZiplineService


import `in`.shabinder.soundbound.utils.GlobalJson
import kotlinx.serialization.Serializable

interface HttpClientBuilder : ZiplineService {
  fun build(enableCookies: Boolean = true): HttpClient
}

fun HttpClientBuilder.build(
  enableCookies: Boolean = true,
  config: HttpClient.() -> Unit
): HttpClient =
  build(enableCookies).apply(config)

interface HttpClient : ZiplineService {

  var isCookiesEnabled: Boolean

  fun getCookies(): Map
  fun setCookie(url: String, cookie: String)

  fun getAuthInfo(): AuthType
  fun setAuth(auth: AuthType)

  fun defaultHeaders(): Map

  fun setDefaultHeaders(headers: Map)

  fun getDefaultURL(): String? = null
  fun setDefaultURL(url: String?)

  fun getDefaultParams(): Map
  fun setDefaultParams(params: Map)

  suspend fun getAsString(
    url: String,
    params: Map = emptyMap(),
    headers: Map = emptyMap(),
  ): String

  suspend fun postAsString(
    url: String,
    params: Map = emptyMap(),
    body: BodyType = BodyType.NONE,
    headers: Map = emptyMap(),
  ): String

  suspend fun getFinalUrl(
    url: String,
    headers: Map = emptyMap(),
  ): String


  @Serializable
  sealed interface AuthType {
    @Serializable
    data object NONE : AuthType

    @Serializable
    data class BASIC(
      val username: String,
      val password: String,
    ) : AuthType

    @Serializable
    data class BEARER(
      val token: String,
    ) : AuthType
  }

  @Serializable

  sealed interface BodyType {
    @Serializable

    data object NONE : BodyType


    @Serializable
    data class JSON(
      val json: String,
    ) : BodyType


    @Serializable
    data class FORM(
      val form: Map,
    ) : BodyType


    @Serializable
    data class RAW(
      val raw: String,
    ) : BodyType
  }


  @Serializable
  enum class Method {
    GET, POST, PUT, DELETE, HEAD
  }
}

suspend inline fun  HttpClient.get(
  url: String,
  params: Map = emptyMap(),
  headers: Map = emptyMap(),
): T {
  return getAsString(url, params, headers).let {
    if (T::class == String::class) {
      return@let it as T
    }

    GlobalJson.decodeFromString(it)
  }
}

suspend inline fun  HttpClient.post(
  url: String,
  params: Map = emptyMap(),
  body: HttpClient.BodyType = HttpClient.BodyType.NONE,
  headers: Map = emptyMap(),
): T {
  return postAsString(url, params, body, headers).let {
    if (T::class == String::class) {
      return@let it as T
    }

    GlobalJson.decodeFromString(it)
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy