|
| 1 | +package com.fernandocejas.sample.core.network |
| 2 | + |
| 3 | +import com.fernandocejas.sample.core.functional.Either |
| 4 | +import com.fernandocejas.sample.core.functional.toLeft |
| 5 | +import com.fernandocejas.sample.core.functional.toRight |
| 6 | + |
| 7 | +sealed class ApiResponse<out T, out E> { |
| 8 | + /** |
| 9 | + * Represents successful network responses (2xx). |
| 10 | + */ |
| 11 | + data class Success<T>(val body: T) : ApiResponse<T, Nothing>() |
| 12 | + |
| 13 | + sealed class Error<E> : ApiResponse<Nothing, E>() { |
| 14 | + /** |
| 15 | + * Represents server (50x) and client (40x) errors. |
| 16 | + */ |
| 17 | + data class HttpError<E>(val code: Int, val errorBody: E?) : Error<E>() |
| 18 | + |
| 19 | + /** |
| 20 | + * Represent IOExceptions and connectivity issues. |
| 21 | + */ |
| 22 | + data object NetworkError : Error<Nothing>() |
| 23 | + |
| 24 | + /** |
| 25 | + * Represent SerializationExceptions. |
| 26 | + */ |
| 27 | + data object SerializationError : Error<Nothing>() |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +// Side Effect helpers |
| 32 | +inline fun <T, E> ApiResponse<T, E>.onSuccess(block: (T) -> Unit): ApiResponse<T, E> { |
| 33 | + if (this is ApiResponse.Success) { |
| 34 | + block(body) |
| 35 | + } |
| 36 | + return this |
| 37 | +} |
| 38 | + |
| 39 | +fun <T, E> ApiResponse<T, E>.toEither(): Either<E?, T> { |
| 40 | + return when (this) { |
| 41 | + is ApiResponse.Success -> body.toRight() |
| 42 | + is ApiResponse.Error.HttpError -> errorBody.toLeft() |
| 43 | + is ApiResponse.Error.NetworkError -> null.toLeft() |
| 44 | + is ApiResponse.Error.SerializationError -> null.toLeft() |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +fun <T, E, F, D> ApiResponse<T, E>.toEither( |
| 49 | + successTransform: (T) -> D, |
| 50 | + errorTransform: (ApiResponse.Error<E>) -> F, |
| 51 | +): Either<F, D> { |
| 52 | + return when (this) { |
| 53 | + is ApiResponse.Success -> successTransform(body).toRight() |
| 54 | + is ApiResponse.Error -> errorTransform(this).toLeft() |
| 55 | + } |
| 56 | +} |
0 commit comments