1
0
mirror of https://github.com/wulkanowy/wulkanowy.git synced 2025-01-19 06:26:51 -06:00

Add auto refresh to reporting units (#1916)

This commit is contained in:
Mikołaj Pich 2022-07-12 12:23:55 +02:00 committed by GitHub
parent bdb6c962ea
commit 7c4f1c7b22
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -5,6 +5,8 @@ import io.github.wulkanowy.data.db.entities.ReportingUnit
import io.github.wulkanowy.data.db.entities.Student
import io.github.wulkanowy.data.mappers.mapToEntities
import io.github.wulkanowy.sdk.Sdk
import io.github.wulkanowy.utils.AutoRefreshHelper
import io.github.wulkanowy.utils.getRefreshKey
import io.github.wulkanowy.utils.init
import io.github.wulkanowy.utils.uniqueSubtract
import javax.inject.Inject
@ -13,30 +15,39 @@ import javax.inject.Singleton
@Singleton
class ReportingUnitRepository @Inject constructor(
private val reportingUnitDb: ReportingUnitDao,
private val sdk: Sdk
private val sdk: Sdk,
private val refreshHelper: AutoRefreshHelper,
) {
private val cacheKey = "reporting_unit"
suspend fun refreshReportingUnits(student: Student) {
val new = sdk.init(student).getReportingUnits().mapToEntities(student)
val old = reportingUnitDb.load(student.id.toInt())
reportingUnitDb.deleteAll(old.uniqueSubtract(new))
reportingUnitDb.insertAll(new.uniqueSubtract(old))
refreshHelper.updateLastRefreshTimestamp(getRefreshKey(cacheKey, student))
}
suspend fun getReportingUnits(student: Student): List<ReportingUnit> {
return reportingUnitDb.load(student.id.toInt()).ifEmpty {
refreshReportingUnits(student)
val cached = reportingUnitDb.load(student.id.toInt())
val isExpired = refreshHelper.shouldBeRefreshed(getRefreshKey(cacheKey, student))
return if (cached.isEmpty() || isExpired) {
refreshReportingUnits(student)
reportingUnitDb.load(student.id.toInt())
}
} else cached
}
suspend fun getReportingUnit(student: Student, unitId: Int): ReportingUnit? {
return reportingUnitDb.loadOne(student.id.toInt(), unitId) ?: run {
refreshReportingUnits(student)
val cached = reportingUnitDb.loadOne(student.id.toInt(), unitId)
val isExpired = refreshHelper.shouldBeRefreshed(getRefreshKey(cacheKey, student))
return reportingUnitDb.loadOne(student.id.toInt(), unitId)
}
return if (cached == null || isExpired) {
refreshReportingUnits(student)
reportingUnitDb.loadOne(student.id.toInt(), unitId)
} else cached
}
}