Create api from user without side effect

This commit is contained in:
Matthieu 2021-08-19 14:35:14 +02:00
parent ba372a3d17
commit 6e1e12af0e
2 changed files with 31 additions and 20 deletions

View File

@ -3,6 +3,11 @@ package org.pixeldroid.app.utils.api
import org.pixeldroid.app.utils.api.objects.*
import io.reactivex.Observable
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import org.pixeldroid.app.utils.db.AppDatabase
import org.pixeldroid.app.utils.db.entities.UserDatabaseEntity
import org.pixeldroid.app.utils.di.PixelfedAPIHolder
import org.pixeldroid.app.utils.di.TokenAuthenticator
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
@ -28,6 +33,30 @@ interface PixelfedAPI {
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build().create(PixelfedAPI::class.java)
}
private val intermediate: Retrofit.Builder = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
fun apiForUser(
user: UserDatabaseEntity,
db: AppDatabase,
pixelfedAPIHolder: PixelfedAPIHolder
): PixelfedAPI =
intermediate
.baseUrl(user.instance_uri)
.client(
OkHttpClient().newBuilder().authenticator(TokenAuthenticator(user, db, pixelfedAPIHolder))
.addInterceptor {
it.request().newBuilder().run {
header("Accept", "application/json")
header("Authorization", "Bearer ${user.accessToken}")
it.proceed(build())
}
}.build()
)
.build().create(PixelfedAPI::class.java)
}

View File

@ -8,9 +8,7 @@ import dagger.Module
import dagger.Provides
import kotlinx.coroutines.runBlocking
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import org.pixeldroid.app.utils.api.PixelfedAPI.Companion.apiForUser
import javax.inject.Singleton
@Module
@ -78,9 +76,6 @@ class TokenAuthenticator(val user: UserDatabaseEntity, val db: AppDatabase, val
}
class PixelfedAPIHolder(private val db: AppDatabase){
private val intermediate: Retrofit.Builder = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
var api: PixelfedAPI? =
db.userDao().getActiveUser()?.let {
@ -90,21 +85,8 @@ class PixelfedAPIHolder(private val db: AppDatabase){
fun setToCurrentUser(
user: UserDatabaseEntity = db.userDao().getActiveUser()!!
): PixelfedAPI {
val newAPI = intermediate
.baseUrl(user.instance_uri)
.client(
OkHttpClient().newBuilder().authenticator(TokenAuthenticator(user, db, this))
.addInterceptor {
it.request().newBuilder().run {
header("Accept", "application/json")
header("Authorization", "Bearer ${user.accessToken}")
it.proceed(build())
}
}.build()
)
.build().create(PixelfedAPI::class.java)
val newAPI = apiForUser(user, db, this)
api = newAPI
return newAPI
}
}