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

dev.inmo.plagubot.KoinExtensions.kt Maven / Gradle / Ivy

The newest version!
package dev.inmo.plagubot

import kotlinx.serialization.InternalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.serializer
import org.jetbrains.exposed.sql.Database
import org.koin.core.Koin
import org.koin.core.module.Module
import org.koin.core.scope.Scope
import kotlin.reflect.KClass

/**
 * Using [single] to register `T` with serializer [configSerializer]
 *
 * @param default Will be used if [field] is absent as an alternative way of config allocation. If null passed, error
 * will be thrown
 */
inline fun  Module.registerConfig(configSerializer: KSerializer, field: String?, noinline default: (Scope.(JsonObject) -> T?)? = null) {
    single {
        val fieldValue = get().let {
            if (field == null) {
                it
            } else {
                it[field] ?: default ?.let { _ ->
                    return@single default(it)
                } ?: error("Unable to take field $field from config")
            }
        }
        get().decodeFromJsonElement(configSerializer, fieldValue)
    }
}

/**
 * Using [single] to register config with getting of [serializer] from [kClass]
 *
 * @param default Will be used if [field] is absent as an alternative way of config allocation. If null passed, error
 * will be thrown
 */
@OptIn(InternalSerializationApi::class)
inline fun  Module.registerConfig(kClass: KClass, field: String?, noinline default: (Scope.(JsonObject) -> T?)? = null) = registerConfig(kClass.serializer(), field, default)

/**
 * Using [single] to register config with getting of [serializer] from [kClass]
 *
 * @param default Will be used if [field] is absent as an alternative way of config allocation. If null passed, error
 * will be thrown
 */
inline fun  Module.registerConfig(field: String?, noinline default: (Scope.(JsonObject) -> T?)? = null) = registerConfig(T::class, field, default)

inline fun  Scope.config() = get()
inline fun  Koin.config() = get()
inline fun  Scope.configOrNull() = getOrNull()
inline fun  Koin.configOrNull() = getOrNull()




© 2015 - 2024 Weber Informatics LLC | Privacy Policy