|
| 1 | +package pokitmons.pokit.data.di.network |
| 2 | + |
| 3 | +import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory |
| 4 | +import dagger.Module |
| 5 | +import dagger.Provides |
| 6 | +import dagger.hilt.InstallIn |
| 7 | +import dagger.hilt.components.SingletonComponent |
| 8 | +import kotlinx.serialization.json.Json |
| 9 | +import okhttp3.MediaType.Companion.toMediaType |
| 10 | +import okhttp3.OkHttpClient |
| 11 | +import okhttp3.logging.HttpLoggingInterceptor |
| 12 | +import pokitmons.pokit.data.api.AuthApi |
| 13 | +import retrofit2.Retrofit |
| 14 | +import java.util.concurrent.TimeUnit |
| 15 | +import javax.inject.Singleton |
| 16 | + |
| 17 | +private const val BASE_URL = "https://pokit.site" |
| 18 | +private const val API = "api" |
| 19 | +private const val VERSION = "v1" |
| 20 | + |
| 21 | +private const val READ_TIME_OUT = 20000L |
| 22 | +private const val WRITE_TIME_OUT = 20000L |
| 23 | + |
| 24 | +@Module |
| 25 | +@InstallIn(SingletonComponent::class) |
| 26 | +object NetworkModule { |
| 27 | + @Singleton |
| 28 | + @Provides |
| 29 | + fun provideOkHttpClient(): OkHttpClient { |
| 30 | + return OkHttpClient.Builder() |
| 31 | + .addInterceptor(BearerTokenInterceptor()) |
| 32 | + .addInterceptor( |
| 33 | + HttpLoggingInterceptor().apply { |
| 34 | + level = HttpLoggingInterceptor.Level.BODY |
| 35 | + } |
| 36 | + ) |
| 37 | + .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS) |
| 38 | + .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS) |
| 39 | + .build() |
| 40 | + } |
| 41 | + |
| 42 | + @Singleton |
| 43 | + @Provides |
| 44 | + fun provideJson(): Json { |
| 45 | + return Json { |
| 46 | + ignoreUnknownKeys = true |
| 47 | + coerceInputValues = true |
| 48 | + prettyPrint = true |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + @Singleton |
| 53 | + @Provides |
| 54 | + fun provideRetrofit( |
| 55 | + okHttpClient: OkHttpClient, |
| 56 | + json: Json, |
| 57 | + ): Retrofit { |
| 58 | + val converterFactory = json.asConverterFactory("application/json; charset=UTF8".toMediaType()) |
| 59 | + return Retrofit.Builder() |
| 60 | + .baseUrl("$BASE_URL/$API/$VERSION/") |
| 61 | + .addConverterFactory(converterFactory) |
| 62 | + .client(okHttpClient) |
| 63 | + .build() |
| 64 | + } |
| 65 | + |
| 66 | + @Provides |
| 67 | + fun provideAuthService(retrofit: Retrofit): AuthApi { |
| 68 | + return retrofit.create(AuthApi::class.java) |
| 69 | + } |
| 70 | +} |
0 commit comments