Created
April 21, 2021 13:53
-
-
Save osipxd/cef631497c8bc2f50d09ec953a89b00c to your computer and use it in GitHub Desktop.
This file contains 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
import com.squareup.moshi.JsonClass | |
import com.squareup.moshi.Types | |
import okhttp3.ResponseBody | |
import retrofit2.Converter | |
import retrofit2.Retrofit | |
import java.lang.reflect.Type | |
/** | |
* Конвертер серверных ответов, построенных на принципе помещения полезной нагрузки в Json-объект data. | |
* Результат конвертации - содержимое data. | |
* Позволяет описывать возвращаемое значение запроса в API в целевом виде - без обертки в data. | |
* | |
* Следует применять, когда все серверные ответы или подавляющее их большинство построено | |
* вышеописанным образом. | |
*/ | |
class EnvelopeJsonConverter<T>( | |
private val delegate: Converter<ResponseBody, Envelope<T>>, | |
) : Converter<ResponseBody, T> { | |
class Factory : Converter.Factory() { | |
override fun responseBodyConverter( | |
type: Type, | |
annotations: Array<Annotation>, | |
retrofit: Retrofit, | |
): Converter<ResponseBody, *>? { | |
val envelopeType = Types.newParameterizedTypeWithOwner( | |
EnvelopeJsonConverter::class.java, | |
Envelope::class.java, | |
type | |
) | |
val delegate = retrofit.nextResponseBodyConverter<Envelope<Any?>>(this, envelopeType, annotations) | |
return EnvelopeJsonConverter(delegate) | |
} | |
} | |
override fun convert(responseBody: ResponseBody): T? { | |
val envelope = delegate.convert(responseBody) | |
return envelope?.data | |
} | |
@JsonClass(generateAdapter = true) | |
class Envelope<T>(internal val data: T) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment