|
| 1 | +package by.jprof.telegram.bot.kotlin.dynamodb.dao |
| 2 | + |
| 3 | +import by.jprof.telegram.bot.kotlin.dao.KotlinMentionsDAO |
| 4 | +import by.jprof.telegram.bot.kotlin.model.KotlinMentions |
| 5 | +import by.jprof.telegram.bot.kotlin.model.UserStatistics |
| 6 | +import by.jprof.telegram.bot.utils.dynamodb.toAttributeValue |
| 7 | +import by.jprof.telegram.bot.utils.dynamodb.toInstant |
| 8 | +import by.jprof.telegram.bot.utils.dynamodb.toLong |
| 9 | +import kotlinx.coroutines.Dispatchers |
| 10 | +import kotlinx.coroutines.future.await |
| 11 | +import kotlinx.coroutines.withContext |
| 12 | +import software.amazon.awssdk.services.dynamodb.DynamoDbAsyncClient |
| 13 | +import software.amazon.awssdk.services.dynamodb.model.AttributeValue |
| 14 | + |
| 15 | +class KotlinMentionsDAO( |
| 16 | + private val dynamoDb: DynamoDbAsyncClient, |
| 17 | + private val table: String |
| 18 | +) : KotlinMentionsDAO { |
| 19 | + override suspend fun save(kotlinMentions: KotlinMentions) { |
| 20 | + withContext(Dispatchers.IO) { |
| 21 | + dynamoDb.putItem { |
| 22 | + it.tableName(table) |
| 23 | + it.item(kotlinMentions.toAttributes()) |
| 24 | + }.await() |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + override suspend fun get(chat: Long): KotlinMentions? { |
| 29 | + return withContext(Dispatchers.IO) { |
| 30 | + dynamoDb.getItem { |
| 31 | + it.tableName(table) |
| 32 | + it.key(mapOf("chat" to chat.toAttributeValue())) |
| 33 | + }.await()?.item()?.takeUnless { it.isEmpty() }?.toKotlinMentions() |
| 34 | + } |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +fun UserStatistics.toAttributes(): Map<String, AttributeValue> = mapOf( |
| 39 | + "count" to this.count.toAttributeValue(), |
| 40 | + "lastMention" to this.lastMention.toAttributeValue(), |
| 41 | +) |
| 42 | + |
| 43 | +fun KotlinMentions.toAttributes(): Map<String, AttributeValue> = mapOf( |
| 44 | + "chat" to this.chat.toAttributeValue(), |
| 45 | + "lastMention" to this.lastMention.toAttributeValue(), |
| 46 | + "usersStatistics" to this.usersStatistics |
| 47 | + .mapKeys { it.key.toString() } |
| 48 | + .mapValues { AttributeValue.builder().m(it.value.toAttributes()).build() } |
| 49 | + .toAttributeValue() |
| 50 | +) |
| 51 | + |
| 52 | +fun Map<String, AttributeValue>.toUserStatistics(): UserStatistics = UserStatistics( |
| 53 | + count = this["count"].toLong("count"), |
| 54 | + lastMention = this["lastMention"].toInstant("lastMention"), |
| 55 | +) |
| 56 | + |
| 57 | +fun Map<String, AttributeValue>.toKotlinMentions(): KotlinMentions = KotlinMentions( |
| 58 | + chat = this["chat"].toLong("chat"), |
| 59 | + lastMention = this["lastMention"].toInstant("lastMention"), |
| 60 | + usersStatistics = this["usersStatistics"]?.m()?.let { |
| 61 | + it |
| 62 | + .mapValues { (_, value) -> value.m().toUserStatistics() } |
| 63 | + .mapKeys { (key, _) -> key.toLong() } |
| 64 | + } ?: emptyMap() |
| 65 | +) |
0 commit comments