com.ecwid.apiclient.v3.impl.ResponseParser.kt Maven / Gradle / Ivy
The newest version!
package com.ecwid.apiclient.v3.impl
import com.ecwid.apiclient.v3.asString
import com.ecwid.apiclient.v3.jsontransformer.JsonTransformer
private const val MAX_LOG_ENTRY_LENGTH = 8_192
interface ResponseParser {
fun parse(responseBytes: ByteArray): V
fun getLogString(responseBytes: ByteArray): String
}
data class ParsedResponseWithExt(
val baseResult: VBase,
val extResult: VExt
)
@PublishedApi
internal class StringResponseParser : ResponseParser {
override fun parse(responseBytes: ByteArray): String {
return responseBytes.asString()
}
override fun getLogString(responseBytes: ByteArray): String {
return responseBytes.asString().abbreviateForLog()
}
}
@PublishedApi
internal class ByteArrayResponseParser : ResponseParser {
override fun parse(responseBytes: ByteArray): ByteArray {
return responseBytes
}
override fun getLogString(responseBytes: ByteArray): String {
return responseBytes.abbreviateForLog()
}
}
@PublishedApi
internal class ObjectResponseParser(
private val jsonTransformer: JsonTransformer,
private val clazz: Class
) : ResponseParser {
override fun parse(responseBytes: ByteArray): V {
return jsonTransformer.deserialize(responseBytes.asString(), clazz)!!
}
override fun getLogString(responseBytes: ByteArray): String {
return responseBytes.asString().abbreviateForLog()
}
}
@PublishedApi
internal class ObjectWithExtResponseParser(
private val jsonTransformer: JsonTransformer,
private val baseClass: Class,
private val extClass: Class
) : ResponseParser> {
override fun parse(responseBytes: ByteArray): ParsedResponseWithExt {
val baseResult = jsonTransformer.deserialize(responseBytes.asString(), baseClass)!!
val extResult = jsonTransformer.deserialize(responseBytes.asString(), extClass)!!
return ParsedResponseWithExt(baseResult, extResult)
}
override fun getLogString(responseBytes: ByteArray): String {
return responseBytes.asString().abbreviateForLog()
}
}
private fun String.abbreviateForLog(): String {
return if (length > MAX_LOG_ENTRY_LENGTH) {
take(MAX_LOG_ENTRY_LENGTH) + "… [$length symbols total]"
} else {
this
}
}
private fun ByteArray.abbreviateForLog(): String {
return "[Binary data: byte array of size $size]"
}