Last active
January 14, 2020 15:06
-
-
Save IosephKnecht/2719ac7e7d47ac7f2ad6048ad0245ac9 to your computer and use it in GitHub Desktop.
Convertation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Интерфейс, который торчит из микросервиса. | |
// Методы дергуются при маршрутизации из приложения. | |
interface PostController { | |
suspend fun createPost(): Post | |
suspend fun readPost(id: UUID): Post? | |
suspend fun updatePost(post: Post): Boolean | |
suspend fun deletePost(id: UUID): Boolean | |
} | |
// Общая модель данных поста. | |
data class Post( | |
val uuid: UUID? = null, | |
val dateCreated: String? = null, | |
val type: PostType? = null, | |
val content: StringBuffer? = null, | |
val owner: Long? = null | |
) { | |
override fun equals(other: Any?): Boolean { | |
if (this === other) return true | |
if (javaClass != other?.javaClass) return false | |
other as Post | |
if (uuid != other.uuid) return false | |
if (dateCreated != other.dateCreated) return false | |
if (type != other.type) return false | |
if (content.toString() != other.content.toString()) return false | |
if (owner != other.owner) return false | |
return true | |
} | |
override fun hashCode(): Int { | |
var result = uuid?.hashCode() ?: 0 | |
result = 31 * result + (dateCreated?.hashCode() ?: 0) | |
result = 31 * result + (type?.hashCode() ?: 0) | |
result = 31 * result + (content?.hashCode() ?: 0) | |
result = 31 * result + (owner?.hashCode() ?: 0) | |
return result | |
} | |
} | |
// Сценарий использования при чтении поста из базы. | |
internal class ReadPostInteractor(private val postRepository: PostRepository) { | |
suspend fun readPost(id: UUID) = coroutineScope { | |
val result = withContext(Dispatchers.IO) { | |
postRepository.readPost(id) | |
} | |
return@coroutineScope result?.let { tuples -> PostMapper.toPost(tuples.first()) } | |
} | |
} | |
// Объект, который конвертирует модель БД в Post туда и обратно. | |
internal object PostMapper { | |
// из модели БД в модель Post | |
@Throws(ClassCastException::class, IndexOutOfBoundsException::class) | |
fun toPost(row: Row): Post { | |
return Post( | |
// Каст | |
uuid = UUID.fromString(row.getString(0)), | |
// Каст | |
dateCreated = row.getString(1), | |
// Каст | |
type = PostType.values()[row.getInteger(2)], | |
// Каст | |
content = StringBuffer(row.getString(3)), | |
// Каст | |
owner = row.getLong(4) | |
) | |
} | |
// из модели Post в модель БД. | |
fun fromPost(post: Post): Tuple { | |
return with(post) { | |
Tuple.of(uuid.toString(), dateCreated, type?.ordinal, content, owner) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment