Skip to content

Commit

Permalink
add/#9: Interceptor 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
youjin09222 committed May 3, 2024
1 parent 0a346e6 commit ad0d55f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
28 changes: 28 additions & 0 deletions app/src/main/java/com/sopt/now/test/data/ApiFactory.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 <reified T> create(): T = retrofit.create(T::class.java)
}

object ServicePool {
val authService = ApiFactory.create<AuthService>()
val userService = ApiFactory.create<UserService>()
}
11 changes: 11 additions & 0 deletions app/src/main/java/com/sopt/now/test/data/UserService.kt
Original file line number Diff line number Diff line change
@@ -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<ResponseUserInfoDto>
}

0 comments on commit ad0d55f

Please sign in to comment.