+ gitignore
+ add boilerplate
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
package com.nano.repository
|
||||
|
||||
import com.nano.db.TaskTable
|
||||
import com.nano.model.Task
|
||||
import com.nano.model.TaskStatus
|
||||
import org.jetbrains.exposed.sql.*
|
||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||
import org.jetbrains.exposed.sql.transactions.transaction
|
||||
import java.time.Instant
|
||||
import java.util.UUID
|
||||
|
||||
class TaskRepository(
|
||||
private val db: Database,
|
||||
) {
|
||||
fun create(task: Task): Task =
|
||||
transaction(db) {
|
||||
val now = Instant.now().toEpochMilli()
|
||||
TaskTable.insert {
|
||||
it[id] = task.id
|
||||
it[name] = task.name
|
||||
it[payload] = task.payload
|
||||
it[status] = task.status
|
||||
it[createdAt] = now
|
||||
it[updatedAt] = now
|
||||
}
|
||||
task.copy(createdAt = now, updatedAt = now)
|
||||
}
|
||||
|
||||
fun findById(id: UUID): Task? =
|
||||
transaction(db) {
|
||||
TaskTable
|
||||
.selectAll()
|
||||
.where(TaskTable.id eq id)
|
||||
.singleOrNull()
|
||||
?.toTask()
|
||||
}
|
||||
|
||||
fun findAll(): List<Task> =
|
||||
transaction(db) {
|
||||
TaskTable
|
||||
.selectAll()
|
||||
.orderBy(TaskTable.createdAt, SortOrder.DESC)
|
||||
.map { it.toTask() }
|
||||
}
|
||||
|
||||
fun findByStatus(status: TaskStatus): List<Task> =
|
||||
transaction(db) {
|
||||
TaskTable
|
||||
.selectAll()
|
||||
.where(TaskTable.status eq status)
|
||||
.orderBy(TaskTable.createdAt, SortOrder.DESC)
|
||||
.map { it.toTask() }
|
||||
}
|
||||
|
||||
fun updateStatus(
|
||||
id: UUID,
|
||||
newStatus: TaskStatus,
|
||||
): Task? =
|
||||
transaction(db) {
|
||||
val now = Instant.now().toEpochMilli()
|
||||
val updated =
|
||||
TaskTable.update({ TaskTable.id eq id }) {
|
||||
it[status] = newStatus
|
||||
it[updatedAt] = now
|
||||
}
|
||||
if (updated == 0) {
|
||||
null
|
||||
} else {
|
||||
findById(id)
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(id: UUID): Boolean =
|
||||
transaction(db) {
|
||||
TaskTable.deleteWhere { TaskTable.id eq id } > 0
|
||||
}
|
||||
|
||||
private fun ResultRow.toTask() =
|
||||
Task(
|
||||
id = this[TaskTable.id],
|
||||
name = this[TaskTable.name],
|
||||
payload = this[TaskTable.payload],
|
||||
status = this[TaskTable.status],
|
||||
createdAt = this[TaskTable.createdAt],
|
||||
updatedAt = this[TaskTable.updatedAt],
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user