core/core/api/src/commonMain/kotlin/dev/inmo/postssystem/core/content/api/business/content_adapters/binary/BinaryBusinessContentRepoCo...

54 lines
2.0 KiB
Kotlin

package dev.inmo.postssystem.core.content.api.business.content_adapters.binary
import dev.inmo.micro_utils.repos.*
import dev.inmo.postssystem.core.content.Content
import dev.inmo.postssystem.core.content.ContentId
import dev.inmo.postssystem.core.content.api.business.AdapterType
import dev.inmo.postssystem.core.content.api.business.BusinessContentRepoContentAdapter
import dev.inmo.postssystem.core.content.api.business.content_adapters.KeyValueBusinessContentRepoAdapter
import kotlinx.serialization.json.Json
private val format = Json { ignoreUnknownKeys = true }
class BinaryBusinessContentRepoContentAdapter(
private val dataStore: KeyValueRepo<ContentId, String>,
private val filesStore: KeyValueRepo<ContentId, ByteArray>,
private val removeOnAbsentInOneOfStores: Boolean = false
) : BusinessContentRepoContentAdapter {
override val type: AdapterType
get() = "binary"
override suspend fun storeContent(contentId: ContentId, content: Content): Boolean {
(content as? BinaryContent) ?.also {
filesStore.set(contentId, it.dataAllocator())
dataStore.set(
contentId,
format.encodeToString(BinaryContent.serializer(), it.copy { ByteArray(0) })
)
} ?: return false
return true
}
override suspend fun getContent(contentId: ContentId): Content? {
return filesStore.get(contentId) ?.let {
val serializedData = dataStore.get(contentId)
if (serializedData != null) {
format.decodeFromString(BinaryContent.serializer(), serializedData).copy {
it
}
} else {
null
}
} ?: null.also {
if (removeOnAbsentInOneOfStores) {
filesStore.unset(contentId)
dataStore.unset(contentId)
}
}
}
override suspend fun removeContent(contentId: ContentId) {
filesStore.unset(contentId)
dataStore.unset(contentId)
}
}