Created
February 9, 2021 07:20
-
-
Save Foreman76/a52eaa120d01953285a7dddfa8a6c716 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
package ru.int24.ownbarbershop | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.withContext | |
import retrofit2.HttpException | |
import ru.int24.ownbarbershop.models.domen.DomServices | |
import ru.int24.ownbarbershop.models.netresult.NetResult | |
import ru.int24.ownbarbershop.network.UseRetrofit | |
import ru.int24.ownbarbershop.network.getHeaders | |
import ru.int24.ownbarbershop.network.safeApiCall | |
import ru.int24.ownbarbershop.repositories.NetworkRepository | |
import java.io.IOException | |
sealed class NetResult<out T> { | |
data class Success<out T>(val value: T): NetResult<T>() | |
data class GenericError(val code: Int? = null, val error: String? = null): NetResult<T>() | |
object NetworkError: NetResult<Nothing>() | |
} | |
interface NetworkRepository { | |
suspend fun getServices(data: Map<String, Any?>): NetResult<List<DomServices>> | |
} | |
suspend fun <T> safeApiCall(apiCall: suspend() -> T): NetResult<T>{ | |
return withContext(Dispatchers.IO){ | |
try { | |
NetResult.Success(apiCall.invoke()) | |
} catch (throwable: Throwable) { | |
when (throwable) { | |
is IOException -> NetResult.NetworkError | |
is HttpException -> { | |
val code = throwable.code() | |
val errorString = "Network error" | |
NetResult.GenericError(code, errorString) | |
} | |
else -> NetResult.GenericError(null, "Network error") | |
} | |
} | |
} | |
} | |
class NetworkRepositoryImpl(): NetworkRepository { | |
override suspend fun getServices(data: Map<String, Any?>): NetResult<List<DomServices>> { | |
val headers = getHeaders(false) | |
val staff_id = data["staff_id"] as Int? | |
val companyid = data["companyid"] as Int | |
val datetime = data["datetime"] as String? | |
val service_ids = data["service_ids"] as String? | |
val serviceResponse = safeApiCall { UseRetrofit.makeRetrofitAPI().getServices(headers = headers, | |
staff_id = staff_id, companyid = companyid, | |
datetime = datetime, service_ids = service_ids)} | |
return serviceResponse.value.body()?.toDomModel() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment