From ad0d55f5958db6f855edd7f817f42929517dc959 Mon Sep 17 00:00:00 2001 From: youjin09222 Date: Fri, 3 May 2024 18:05:06 +0900 Subject: [PATCH] =?UTF-8?q?add/#9:=20Interceptor=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/sopt/now/test/data/ApiFactory.kt | 28 +++++++++++++++++++ .../com/sopt/now/test/data/UserService.kt | 11 ++++++++ 2 files changed, 39 insertions(+) create mode 100644 app/src/main/java/com/sopt/now/test/data/UserService.kt diff --git a/app/src/main/java/com/sopt/now/test/data/ApiFactory.kt b/app/src/main/java/com/sopt/now/test/data/ApiFactory.kt index ef33f15..5912b8d 100644 --- a/app/src/main/java/com/sopt/now/test/data/ApiFactory.kt +++ b/app/src/main/java/com/sopt/now/test/data/ApiFactory.kt @@ -3,22 +3,50 @@ package com.sopt.now.test.data import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import com.sopt.now.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 + private lateinit var userPreference: UserPreference // UserPreference 추가 + + // UserPreference 초기화 + fun initializeUserPreference(userPreference: UserPreference) { + this.userPreference = userPreference + } val retrofit: Retrofit by lazy { Retrofit.Builder() .baseUrl(BASE_URL) + .client(provideOkHttpClient(HeaderInterceptor())) .addConverterFactory(Json.asConverterFactory("application/json".toMediaType())) .build() } + private fun provideOkHttpClient(interceptor: HeaderInterceptor): OkHttpClient + = OkHttpClient.Builder().run { + addInterceptor(interceptor) + build() + } + + class HeaderInterceptor : Interceptor { + @Throws(IOException::class) + override fun intercept(chain: Interceptor.Chain) : Response = with(chain) { + val newRequest = request().newBuilder() + .addHeader("memberId", userPreference.getUserId().toString()) + .build() + 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 diff --git a/app/src/main/java/com/sopt/now/test/data/UserService.kt b/app/src/main/java/com/sopt/now/test/data/UserService.kt new file mode 100644 index 0000000..e3a8262 --- /dev/null +++ b/app/src/main/java/com/sopt/now/test/data/UserService.kt @@ -0,0 +1,11 @@ +package com.sopt.now.test.data + +import com.sopt.now.test.data.dto.response.ResponseUserInfoDto +import retrofit2.Call +import retrofit2.http.GET + +interface UserService { + @GET("member/info") + fun userInfo( + ): Call +} \ No newline at end of file