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

run.smt.ktest.db.query.impl.BaseResponse.kt Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
package run.smt.ktest.db.query.impl

import run.smt.ktest.db.query.Response
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.jdbc.core.JdbcTemplate
import kotlin.reflect.KClass

/**
 * Response that can be represented as list, map or single pojo
 */
class BaseResponse(
    klass: KClass,
    jdbc: JdbcTemplate,
    private val listLoader: (JdbcTemplate) -> List,
    private val mapLoader: (JdbcTemplate) -> Map?,
    private val singleLoader: (JdbcTemplate) -> T?
) : Response {

    val asList: List by lazy {
        listLoader(jdbc)
    }

    val asMap: Map? by lazy {
        nullOnEmptyResultDataAccessException(mapLoader)(jdbc)
    }

    @Suppress("UNCHECKED_CAST")
    val single: T? by lazy {
        if (klass == Map::class) {
            mapLoader(jdbc) as T?
        } else {
            nullOnEmptyResultDataAccessException(singleLoader)(jdbc)
        }
    }

    override fun asList(): List {
        return asList
    }

    override fun asMap(): Map? {
        return asMap
    }

    override fun single(): T? {
        return single
    }

    private fun  nullOnEmptyResultDataAccessException(f: (JdbcTemplate) -> R?): (JdbcTemplate) -> R? {
        return {
            try {
                f(it)
            } catch (e: EmptyResultDataAccessException) {
                null
            }
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy