All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.MemoryIndividualAggregateStore.kt Maven / Gradle / Ivy

package io.fluidsonic.raptor.domain.memory

import io.fluidsonic.raptor.domain.*


private class MemoryIndividualAggregateStore> :
	RaptorIndividualAggregateStore {

	private val cache: MutableMap>> = hashMapOf()
	private var lastEventId: RaptorAggregateEventId? = null


	private fun appendToCache(id: Id, events: List>) {
		cache.compute(id) { _, previousEvents ->
			previousEvents.orEmpty() + events
		}

		lastEventId = events.last().id
	}


	override suspend fun lastEventId(): RaptorAggregateEventId? =
		lastEventId


	override suspend fun load(id: Id): List> =
		cache[id].orEmpty()


	override suspend fun reload(): List> {
		cache.clear()

		return emptyList()
	}


	override suspend fun save(id: Id, events: List>) {
		if (events.isEmpty())
			return

		require(events.all { it.aggregateId == id }) { "All events must have aggregate id '$id': $events" }

		var minimumEventId = lastEventId?.toLong() ?: 0
		events.forEachIndexed { index, event ->
			require(event.id.toLong() > minimumEventId) { "Event ${index + 1} ID ${event.id} must be > $minimumEventId: $events" }
			minimumEventId = event.id.toLong()
		}

		appendToCache(id, events)
	}
}


public fun RaptorIndividualAggregateStore.Companion.memory(): RaptorIndividualAggregateStore<*, *> =
	MemoryIndividualAggregateStore>()


@JvmName("memoryGeneric")
@Suppress("UNCHECKED_CAST")
public inline fun >
	RaptorIndividualAggregateStore.Companion.memory(): RaptorIndividualAggregateStore =
	memory() as RaptorIndividualAggregateStore




© 2015 - 2025 Weber Informatics LLC | Privacy Policy