Files
wahlrecht/module-server/src/main/kotlin/de/twomartens/wahlrecht/service/CandidateService.kt
T
2023-07-30 18:17:40 +02:00

36 lines
1.1 KiB
Kotlin

package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.model.db.Candidate
import de.twomartens.wahlrecht.repository.CandidateRepository
import org.springframework.stereotype.Service
@Service
class CandidateService(private val repository: CandidateRepository) {
private val candidates: MutableMap<String, Candidate> by lazy {
fetchCandidates()
}
fun storeCandidate(candidate: Candidate): Candidate {
var result = candidate
val existing = candidates[candidate.name]
val needsUpdate = candidate != existing
if (!needsUpdate && existing != null) {
return existing
}
if (existing != null) {
existing.profession = candidate.profession
result = existing
}
result = repository.save(result)
candidates[candidate.name] = candidate
return result
}
private fun fetchCandidates(): MutableMap<String, Candidate> {
return repository.findAll().asSequence()
.map { Pair(it.name, it) }
.toMap()
.toMutableMap()
}
}