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

me.redtea.carcadex.data.kotlinextensions.RepoExtensions.kt Maven / Gradle / Ivy

There is a newer version: 2.0.1-BETA
Show newest version
package me.redtea.carcadex.data.kotlinextensions

import me.redtea.carcadex.data.repo.MutableRepo
import me.redtea.carcadex.data.repo.builder.RepoBuilder
import me.redtea.carcadex.data.repo.builder.exception.NotConfiguredException
import me.redtea.carcadex.data.schema.file.impl.serialize.SerializeSchemaStrategy
import me.redtea.carcadex.data.serializer.CommonSerializer
import java.io.File

fun repo(folder: File, init: RepoBuilderKt.() -> Unit): MutableRepo {
    val builder = decorator(RepoBuilder.get())
    builder.folder(folder)
    builder.init()
    builder.wrapSchema()
    return builder.build()
}

fun repo(init: RepoBuilderKt.() -> Unit): MutableRepo {
    val builder = decorator(RepoBuilder.get())
    builder.init()
    builder.wrapSchema()
    return builder.build()
}

fun  RepoBuilderKt.save(lambda: (V) -> String) {
    this.save = lambda
}

fun  RepoBuilderKt.load(lambda: ((String) -> V)) {
    this.load = lambda
}

private fun decorator(repoBuilder: RepoBuilder): RepoBuilderKt = RepoBuilderKt(repoBuilder)
class RepoBuilderKt(private val repoBuilder: RepoBuilder) : RepoBuilder by repoBuilder {
    var save: ((V) -> String)? = null
    var load: ((String) -> V)? = null
    var fileExt: String? = null

    private var folder: File? = null
    override fun folder(folder: File?): RepoBuilder {
        this.folder = folder
        return repoBuilder.folder(folder)
    }

    fun wrapSchema(): RepoBuilderKt {
        if(save == null || load == null) return this
        schema(
            SerializeSchemaStrategy(
            folder,
            object : CommonSerializer {
                override fun serialize(v: V): String = (save
                    ?: throw NotConfiguredException("missed save function"))(
                    v
                )

                override fun deserialize(s: String): V = (load
                    ?: throw NotConfiguredException("missed save function"))(
                    s
                )
            }, fileExt ?: ""
        )
        )
        return this
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy