class RepoElement<E>(
val elem: E,
val version: Long
)
class ListRepo<E> : Repo<E> {
private val list = ConcurrentHashMap<String, RepoElement<E>>()
private fun version() = System.currentTimeMillis()
override fun create(element: E): Boolean =
true.apply {
list[UUID.randomUUID().toString()] =
RepoElement(element, version())
}
override fun read(): List<Item<E>> =
list.map {
Item(it.value.elem, it.key, it.value.version)
}
override fun update(item: Item<E>): Boolean =
list[item.id]?.let {
if (it.version==item.version){
list[item.id]= RepoElement(item.elem, version())
true
} else {
false
}
}?: false
put {
val newItem =
Json.decodeFromString(itemSerializer, call.receive())
repo.read(newItem.id) ?: return@put ...
if(repo.update(newItem)) {
call.respondText(
"Element updates correctly",
status = HttpStatusCode.Created)
} else {
call.respondText(
"Element had updated on server",
status = HttpStatusCode.BadRequest)
}
}
post(AddStudentToLesson.path) {
val command = Json.decodeFromString(
AddStudentToLesson.serializer(), call.receive())
val lesson = lessonsRepo.read ...
studentsRepo.read ...
if (lesson.elem.students.find {
it.studentId == command.lessonId } != null) ...
if (command.version != lesson.version) {
call.respondText(
"Lesson had updated on server",
status = HttpStatusCode.BadRequest)}
val newLesson = lesson.elem.addStudent(command.studentId)
...