PlaguPoster/posts/src/jvmMain/kotlin/cached/CachedPostsRepo.kt

55 lines
2.2 KiB
Kotlin
Raw Normal View History

2023-01-18 17:22:49 +00:00
package dev.inmo.plaguposter.posts.cached
2023-11-06 12:59:17 +00:00
import dev.inmo.micro_utils.coroutines.SmartRWLocker
2023-08-12 17:58:28 +00:00
import korlibs.time.DateTime
2023-01-18 17:22:49 +00:00
import dev.inmo.micro_utils.pagination.FirstPagePagination
import dev.inmo.micro_utils.pagination.firstPageWithOneElementPagination
import dev.inmo.micro_utils.pagination.utils.doForAllWithNextPaging
import dev.inmo.micro_utils.repos.CRUDRepo
2023-11-06 12:59:17 +00:00
import dev.inmo.micro_utils.repos.KeyValueRepo
import dev.inmo.micro_utils.repos.MapKeyValueRepo
2023-01-18 17:22:49 +00:00
import dev.inmo.micro_utils.repos.cache.cache.FullKVCache
import dev.inmo.micro_utils.repos.cache.full.FullCRUDCacheRepo
import dev.inmo.plaguposter.posts.models.NewPost
import dev.inmo.plaguposter.posts.models.PostContentInfo
import dev.inmo.plaguposter.posts.models.PostId
import dev.inmo.plaguposter.posts.models.RegisteredPost
import dev.inmo.plaguposter.posts.repo.PostsRepo
import dev.inmo.tgbotapi.types.IdChatIdentifier
2024-04-24 06:14:33 +00:00
import dev.inmo.tgbotapi.types.MessageId
2023-01-18 17:22:49 +00:00
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
class CachedPostsRepo(
private val parentRepo: PostsRepo,
private val scope: CoroutineScope,
2023-11-06 12:59:17 +00:00
private val kvCache: KeyValueRepo<PostId, RegisteredPost> = MapKeyValueRepo()
2023-01-18 17:22:49 +00:00
) : PostsRepo, CRUDRepo<RegisteredPost, PostId, NewPost> by FullCRUDCacheRepo(
parentRepo,
kvCache,
scope,
2023-08-12 17:58:28 +00:00
skipStartInvalidate = false,
2023-11-06 12:59:17 +00:00
locker = SmartRWLocker(),
2023-01-18 17:22:49 +00:00
{ it.id }
) {
override val removedPostsFlow: Flow<RegisteredPost> by parentRepo::removedPostsFlow
2024-04-24 06:14:33 +00:00
override suspend fun getIdByChatAndMessage(chatId: IdChatIdentifier, messageId: MessageId): PostId? {
2023-01-18 17:22:49 +00:00
doForAllWithNextPaging(firstPageWithOneElementPagination) {
kvCache.values(it).also {
it.results.forEach {
return it.takeIf {
it.content.any { it.chatId == chatId && it.messageId == messageId }
} ?.id ?: return@forEach
}
}
}
return null
}
2023-01-18 17:39:56 +00:00
override suspend fun getPostCreationTime(postId: PostId): DateTime? = getById(postId) ?.created
2023-01-18 17:22:49 +00:00
2023-01-18 17:39:56 +00:00
override suspend fun getFirstMessageInfo(postId: PostId): PostContentInfo? = getById(postId) ?.content ?.firstOrNull()
2023-01-18 17:22:49 +00:00
}