58 lines
1.5 KiB
Kotlin
58 lines
1.5 KiB
Kotlin
package chats.data.local.mappers
|
|
|
|
import chats.data.local.database.ChatEntity
|
|
import chats.domain.model.Chat
|
|
import com.google.gson.Gson
|
|
|
|
private val gson = Gson()
|
|
|
|
/**
|
|
* Преобразует Domain Chat в Entity
|
|
*/
|
|
fun Chat.toEntity(): ChatEntity {
|
|
val timestamp = this.lastMessage?.createdAt?.let { parseTimestamp(it) }
|
|
return ChatEntity(
|
|
localId = this.id.takeIf { it.isNotBlank() } ?: java.util.UUID.randomUUID().toString(),
|
|
remoteId = this.id,
|
|
type = this.type,
|
|
name = this.name,
|
|
avatar = this.avatar,
|
|
unreadCount = this.unreadCount,
|
|
lastMessageText = this.lastMessage?.content,
|
|
lastMessageTimestamp = timestamp,
|
|
lastMessageJson = this.lastMessage?.let { gson.toJson(it) }
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Преобразует Entity в Domain Chat
|
|
*/
|
|
fun ChatEntity.toDomain(): Chat {
|
|
val lastMessage = this.lastMessageJson?.let { json ->
|
|
try {
|
|
gson.fromJson(json, chats.domain.model.Message::class.java)
|
|
} catch (e: Exception) {
|
|
null
|
|
}
|
|
}
|
|
return Chat(
|
|
id = this.remoteId ?: this.localId,
|
|
type = this.type,
|
|
name = this.name,
|
|
avatar = this.avatar,
|
|
unreadCount = this.unreadCount,
|
|
lastMessage = lastMessage
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Парсит ISO-8601 timestamp в Long (millis)
|
|
*/
|
|
private fun parseTimestamp(isoTimestamp: String): Long? {
|
|
return try {
|
|
java.time.ZonedDateTime.parse(isoTimestamp).toInstant().toEpochMilli()
|
|
} catch (e: Exception) {
|
|
null
|
|
}
|
|
}
|