2023-11-10 11:06:14 +05:30

75 lines
2.7 KiB
Kotlin

package com.restapi.domain
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.Module
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.restapi.config.AppConfig.Companion.appConfig
import io.ebean.Database
import io.ebean.DatabaseFactory
import io.ebean.config.CurrentTenantProvider
import io.ebean.config.CurrentUserProvider
import io.ebean.config.DatabaseConfig
import io.ebean.config.TenantMode
import java.util.*
data class CurrentUser(
val anon: Boolean = true,
val userId: String = "",
val tenantId: String = ""
)
object Session {
private val currentUser = object : ThreadLocal<CurrentUser>() {
override fun initialValue(): CurrentUser {
return CurrentUser()
}
}
private val sc = DatabaseConfig().apply {
loadFromProperties(Properties().apply {
setProperty("datasource.db.username", appConfig.dbUser())
setProperty("datasource.db.password", appConfig.dbPass())
setProperty("datasource.db.url", appConfig.dbUrl())
setProperty("ebean.migration.run", appConfig.dbRunMigration().toString())
})
tenantMode = TenantMode.PARTITION
currentTenantProvider = CurrentTenantProvider { currentUser.get().tenantId }
currentUserProvider = CurrentUserProvider { currentUser.get().userId }
}
val database: Database = DatabaseFactory.create(sc)
val objectMapper = jacksonObjectMapper().apply {
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
findAndRegisterModules()
}
fun currentUser() = currentUser.get().userId
fun Database.findByEntityAndId(entity: String, id: String): DataModel {
return find(DataModel::class.java)
.where()
.eq("uniqueIdentifier", id)
.eq("entityName", entity)
.findOne() ?: throw DataNotFoundException
}
private fun seqName(entity: String) = "sequence_$entity"
fun creatSeq(entity: String): Int {
return database.sqlUpdate("CREATE SEQUENCE IF NOT EXISTS ${seqName(entity)} START 1;").execute()
}
fun nextUniqId(entity: String): String {
val s = database
.sqlQuery("SELECT nextval('${seqName(entity)}');")
.findOne()?.getLong("nextval") ?: throw DataNotFoundException
return String.format("%s-%s", entity, "$s".padStart(10, '0'))
}
}
object DataNotFoundException : Exception() {
private fun readResolve(): Any = DataNotFoundException
}