Advertisement
Kostiggig

Untitled

Feb 12th, 2022
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.67 KB | None | 0 0
  1. abstract class BaseRepository<T : WithFailureMessage<T>>(private val exceptionMapper: ExceptionMapper) {
  2.  
  3.     suspend fun doRequest(fail: T,block: suspend () -> T) : T {
  4.         return try {
  5.             block.invoke()
  6.         } catch (e: java.lang.Exception) {
  7.             fail.withMessage(exceptionMapper.map(e))
  8.         }
  9.     }
  10. }
  11.  
  12. // Example usage
  13.  
  14. interface AuthRepository {
  15.  
  16.     suspend fun login(auth: Auth) : DataAuth
  17.  
  18.     suspend fun register(auth: Auth) : DataAuth
  19.  
  20.     class Base(
  21.         private val authCloudDataSource: AuthCloudDataSource,
  22.         private val mapper: CloudToDataAuthMapper,
  23.         private val authSharedPreferences: AuthSharedPreferences,
  24.         exceptionMapper: ExceptionMapper
  25.     ) : AuthRepository, BaseRepository<DataAuth>(exceptionMapper) {
  26.  
  27.         override suspend fun login(auth: Auth): DataAuth
  28.             = doRequest(DataAuth.Empty) { authCloudDataSource.login(auth).map(mapper) }
  29.  
  30.  
  31.         override suspend fun register(auth: Auth): DataAuth {
  32.             val result = doRequest(DataAuth.Empty) { authCloudDataSource.register(auth).map(mapper) }
  33.             result.save(authSharedPreferences)
  34.             return result
  35.         }
  36.     }
  37.    
  38.     interface WithFailureMessage<T> {
  39.  
  40.          fun withMessage(message: String) : T
  41.     }
  42.    
  43.    
  44.     sealed class DataAuth : WithFailureMessage<DataAuth> {
  45.    
  46.     data class Failure(
  47.         private val message: String
  48.     ) : DataAuth() {
  49.  
  50.         override fun <T> map(mapper: Abstract.AuthMapper<T>): T
  51.             = mapper.map(message)
  52.     }
  53.  
  54.     object Empty : DataAuth() {
  55.         override fun withMessage(message: String): DataAuth = Failure(message)
  56.     }
  57.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement