AuthRepository.kt fix
Some checks failed
Android Test / validate-and-test (pull_request) Has been cancelled

This commit is contained in:
2025-11-29 18:08:05 +03:00
parent bc7e14ab06
commit 2ecbc7339a
5 changed files with 90 additions and 2 deletions

View File

@@ -0,0 +1,54 @@
package ru.myitschool.work.data.repo
import ru.myitschool.work.data.source.NetworkDataSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import ru.myitschool.work.domain.auth.entities.BookingEntity
import ru.myitschool.work.domain.auth.entities.UserEntity
import kotlinx.serialization.json.Json
object MainRepository {
@Serializable
data class BookingDto(
val roomName: String,
val time: String
)
@Serializable
data class UserDto(
val name: String,
val bookingList: List<BookingDto>
)
private val json = Json { ignoreUnknownKeys = true }
private var codeCache: String? = null
private var cachedUser: UserEntity? = null
suspend fun getUserInfo(code: String): Result<UserEntity> {
return withContext(Dispatchers.IO) {
runCatching {
if (codeCache == code && cachedUser != null) return@runCatching cachedUser!!
codeCache = code
val isAuth = NetworkDataSource.checkAuth(code).getOrThrow()
if (!isAuth) throw Exception("Авторизация не пройдена")
val userJson = NetworkDataSource.getUserData(code).getOrThrow()
val userResponse = json.decodeFromString<UserDto>(userJson)
val user = UserEntity(
name = userResponse.name,
bookingList = userResponse.bookingList.map { BookingEntity(it.roomName, it.time) }
)
cachedUser = user
user
}
}
}
}

View File

@@ -29,7 +29,7 @@ object NetworkDataSource {
}
suspend fun checkAuth(code: String): Result<Boolean> = withContext(Dispatchers.IO) {
return@withContext runCatching {
runCatching {
val response = client.get(getUrl(code, Constants.AUTH_URL))
when (response.status) {
HttpStatusCode.OK -> true
@@ -38,5 +38,15 @@ object NetworkDataSource {
}
}
suspend fun getUserData(code: String): Result<String> = withContext(Dispatchers.IO) {
runCatching {
val response = client.get(getUrl(code, Constants.INFO_URL))
when (response.status) {
HttpStatusCode.OK -> response.bodyAsText()
else -> error(response.bodyAsText())
}
}
}
private fun getUrl(code: String, targetUrl: String) = "${Constants.HOST}/api/$code$targetUrl"
}
}

View File

@@ -0,0 +1,12 @@
package ru.myitschool.work.domain.auth
import ru.myitschool.work.data.repo.MainRepository
import ru.myitschool.work.domain.auth.entities.UserEntity
class GetUserInfoUseCase(
private val repository: MainRepository
) {
suspend operator fun invoke(code: String): Result<UserEntity> {
return repository.getUserInfo(code)
}
}

View File

@@ -0,0 +1,6 @@
package ru.myitschool.work.domain.auth.entities
data class BookingEntity(
val roomName: String,
val time: String,
)

View File

@@ -0,0 +1,6 @@
package ru.myitschool.work.domain.auth.entities
data class UserEntity(
val name: String,
val bookingList: List<BookingEntity>
)