run.smt.ktest.db.query.impl.BaseResponse.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ktest-db Show documentation
Show all versions of ktest-db Show documentation
Database intergration for kTest
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