commonMain.s2.sourcing.dsl.snap.SnapLoader.kt Maven / Gradle / Ivy
package s2.sourcing.dsl.snap
import kotlinx.coroutines.flow.Flow
import s2.dsl.automate.Evt
import s2.dsl.automate.model.WithS2Id
import s2.sourcing.dsl.Loader
import s2.sourcing.dsl.view.ViewLoader
class SnapLoader(
private val snapRepository: SnapRepository,
private val viewLoader: ViewLoader
): Loader where
EVENT: Evt,
EVENT: WithS2Id,
ENTITY: WithS2Id {
override suspend fun load(id: ID & Any): ENTITY? {
return snapRepository.get(id) ?: viewLoader.load(id)
}
override suspend fun loadAndEvolve(id: ID & Any, news: Flow): ENTITY? {
return load(id).let { entity ->
viewLoader.evolve(news, entity)
}
}
override suspend fun load(events: Flow): ENTITY? {
return viewLoader.load(events)
}
override suspend fun evolve(events: Flow, entity: ENTITY?): ENTITY? {
return viewLoader.evolve(events, entity)
}
override suspend fun reloadHistory(): List {
return viewLoader.reloadHistory().onEach { entity ->
snapRepository.remove(entity.s2Id())
snapRepository.save(entity)
}
}
}