From f51e011f2048d43dbcb3e33e6c3e424efe08d75b Mon Sep 17 00:00:00 2001 From: youjin09222 Date: Fri, 3 May 2024 23:29:26 +0900 Subject: [PATCH] =?UTF-8?q?feat/#11:=20ApiFactory=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/sopt/now/compose/data/ApiFactory.kt | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 app/src/main/java/com/sopt/now/compose/data/ApiFactory.kt diff --git a/app/src/main/java/com/sopt/now/compose/data/ApiFactory.kt b/app/src/main/java/com/sopt/now/compose/data/ApiFactory.kt new file mode 100644 index 0000000..83dacdd --- /dev/null +++ b/app/src/main/java/com/sopt/now/compose/data/ApiFactory.kt @@ -0,0 +1,55 @@ +package com.sopt.now.compose.data + +import android.util.Log +import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory +import com.sopt.now.compose.BuildConfig +import kotlinx.serialization.json.Json +import okhttp3.Interceptor +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Response +import retrofit2.Retrofit +import java.io.IOException + +object ApiFactory { + private const val BASE_URL: String = BuildConfig.AUTH_BASE_URL + lateinit var userPreference: UserPreference + + fun initializeUserPreference(userPreference: UserPreference) { + ApiFactory.userPreference = userPreference + } + + val retrofit: Retrofit by lazy { + Retrofit.Builder() + .baseUrl(BASE_URL) + .client(provideOkHttpClient()) + .addConverterFactory(Json.asConverterFactory("application/json".toMediaType())) + .build() + } + + private fun provideOkHttpClient(): OkHttpClient = OkHttpClient.Builder() + .addInterceptor(HeaderInterceptor()) + .build() + + class HeaderInterceptor : Interceptor { + @Throws(IOException::class) + override fun intercept(chain: Interceptor.Chain): Response { + if (!ApiFactory::userPreference.isInitialized) { + throw IllegalStateException("UserPreference is not initialized") + } + + val newRequest = chain.request().newBuilder() + .addHeader("memberId", userPreference.getUserId().toString()) + .build() + Log.d("userPreference API", "${userPreference.getUserId().toString()}") + return chain.proceed(newRequest) + } + } + + inline fun create(): T = retrofit.create(T::class.java) +} + +object ServicePool { + val authService = ApiFactory.create() + val userService = ApiFactory.create() +} \ No newline at end of file