Skip to content

Instantly share code, notes, and snippets.

@dead8309
Created January 29, 2024 07:07
Show Gist options
  • Select an option

  • Save dead8309/f8521cb25c0ad01e0ded2b915145a5be to your computer and use it in GitHub Desktop.

Select an option

Save dead8309/f8521cb25c0ad01e0ded2b915145a5be to your computer and use it in GitHub Desktop.
package `in`.iot.lab.teacherreview.feature_teacherlist.data.data_source.remote
import android.util.Log
import com.google.firebase.Firebase
import com.google.firebase.auth.auth
import `in`.iot.lab.teacherreview.core.utils.Constants.BASE_URL
import `in`.iot.lab.teacherreview.feature_teacherlist.data.data_source.remote.RetrofitInstance.apiInstance
import `in`.iot.lab.teacherreview.feature_teacherlist.data.data_source.remote.RetrofitInstance.retrofit
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
* This is the Retrofit Instance Object which have a retrofit instance which is getting used
* all around this module in the App
*
* @property retrofit This variable is private and contains the Build Features
* @property apiInstance This is public and contains the object of the class Implemented by the
* retrofit Library
*/
object RetrofitInstance {
private val client by lazy {
OkHttpClient.Builder()
.addInterceptor(AuthInterceptor)
.readTimeout(45, TimeUnit.SECONDS)
.writeTimeout(45, TimeUnit.SECONDS)
.build()
}
// Contains the Base Url which gives all the details from the Database
private val retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
// Variable which can be used to call all the functions of the RetrofitApi interface
val apiInstance: RetrofitApi by lazy {
retrofit.create(RetrofitApi::class.java)
}
// TODO: Change this as when the user logs out the token is still there because this is a singleton object
private val AuthInterceptor = object: Interceptor {
private var token = Firebase.auth.currentUser?.getIdToken(false)?.result?.token
?: throw Exception("Token is null");
override fun intercept(chain: Interceptor.Chain): Response {
Log.i("RetrofitInstance", "intercept: $token")
val request = chain
.request()
.newBuilder()
.addHeader("Authorization", token)
.build()
return chain.proceed(request)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment