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

commonMain.net.folivo.trixnity.clientserverapi.client.UIA.kt Maven / Gradle / Ivy

There is a newer version: 4.11.2
Show newest version
package net.folivo.trixnity.clientserverapi.client

import io.ktor.http.*
import net.folivo.trixnity.clientserverapi.model.uia.AuthenticationRequest
import net.folivo.trixnity.clientserverapi.model.uia.AuthenticationType
import net.folivo.trixnity.clientserverapi.model.uia.UIAState
import net.folivo.trixnity.core.ErrorResponse

sealed interface UIA {
    data class Success(
        val value: T
    ) : UIA

    data class Step(
        val state: UIAState,
        private val getFallbackUrlCallback: (AuthenticationType) -> Url,
        private val authenticateCallback: suspend (AuthenticationRequest) -> Result>,
        private val onSuccessCallback: suspend () -> Unit = {}
    ) : UIA {
        fun getFallbackUrl(authenticationType: AuthenticationType): Url =
            getFallbackUrlCallback(authenticationType)

        suspend fun authenticate(request: AuthenticationRequest): Result> =
            authenticateCallback(request).mapCatching {
                it.injectOnSuccessIntoUIA(onSuccessCallback)
            }
    }

    data class Error(
        val state: UIAState,
        val errorResponse: ErrorResponse,
        private val getFallbackUrlCallback: (AuthenticationType) -> Url,
        private val authenticateCallback: suspend (AuthenticationRequest) -> Result>,
        private val onSuccessCallback: suspend () -> Unit = {}
    ) : UIA {
        fun getFallbackUrl(authenticationType: AuthenticationType): Url =
            getFallbackUrlCallback(authenticationType)

        suspend fun authenticate(request: AuthenticationRequest): Result> =
            authenticateCallback(request).mapCatching {
                it.injectOnSuccessIntoUIA(onSuccessCallback)
            }
    }
}

suspend fun  UIA.injectOnSuccessIntoUIA(onSuccessCallback: suspend () -> Unit = {}): UIA {
    return when (this) {
        is UIA.Success -> this.also { onSuccessCallback() }
        is UIA.Step -> this.copy(onSuccessCallback = onSuccessCallback)
        is UIA.Error -> this.copy(onSuccessCallback = onSuccessCallback)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy