Skip to content

Commit

Permalink
[add/#12] reqres api
Browse files Browse the repository at this point in the history
reqres api 연결
- LIST USERS api 사용
  • Loading branch information
Jokwanhee committed Nov 12, 2023
1 parent b0c6e65 commit 34eaa99
Show file tree
Hide file tree
Showing 22 changed files with 190 additions and 40 deletions.
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ android {
versionName "1.0"

buildConfigField "String", "BASE_URL", properties["base.url"]
buildConfigField "String", "USER_BASE_URL", properties["user.base.url"]

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
Expand Down
21 changes: 15 additions & 6 deletions app/src/main/java/org/sopt/dosopttemplate/DoSoptApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ package org.sopt.dosopttemplate
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import org.sopt.dosopttemplate.db.remote.ApiHelper
import org.sopt.dosopttemplate.db.remote.AuthApiHelper
import org.sopt.dosopttemplate.db.remote.RetrofitServicePool
import org.sopt.dosopttemplate.db.remote.UserApiHelper

class DoSoptApp : Application() {
override fun onCreate() {
Expand All @@ -14,7 +15,8 @@ class DoSoptApp : Application() {

companion object {
lateinit var sharedPreferencesInstance: SharedPreferences
private lateinit var apiHelper: ApiHelper
private lateinit var authApiHelper: AuthApiHelper
private lateinit var userApiHelper: UserApiHelper

@Synchronized
private fun getSharedPreferencesInstance(context: Context): SharedPreferences {
Expand All @@ -27,11 +29,18 @@ class DoSoptApp : Application() {
return sharedPreferencesInstance
}

fun getApiHelperInstance(): ApiHelper {
if (!::apiHelper.isInitialized) {
apiHelper = ApiHelper(RetrofitServicePool.authService)
fun getApiHelperInstance(): AuthApiHelper {
if (!::authApiHelper.isInitialized) {
authApiHelper = AuthApiHelper(RetrofitServicePool.authService)
}
return apiHelper
return authApiHelper
}

fun getUserApiHelperInstance(): UserApiHelper {
if (!::userApiHelper.isInitialized) {
userApiHelper = UserApiHelper(RetrofitServicePool.userService)
}
return userApiHelper
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package org.sopt.dosopttemplate.api

import org.sopt.dosopttemplate.model.dto.req.LoginReq
import org.sopt.dosopttemplate.model.dto.req.SignUpReq
import org.sopt.dosopttemplate.model.dto.resp.LoginResp
import org.sopt.dosopttemplate.model.dto.resp.auth.LoginResp
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST

interface RetrofitService {
interface AuthAPI {
@POST("api/v1/members")
fun signUp(
@Body signUpReq: SignUpReq,
Expand Down
13 changes: 13 additions & 0 deletions app/src/main/java/org/sopt/dosopttemplate/api/UserAPI.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.sopt.dosopttemplate.api

import org.sopt.dosopttemplate.model.dto.resp.user.UserResp
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface UserAPI {
@GET("api/users")
fun getUserList(
@Query("page") page: Int
): Call<UserResp>
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
package org.sopt.dosopttemplate.db.remote

import org.sopt.dosopttemplate.api.RetrofitService
import org.sopt.dosopttemplate.api.AuthAPI
import org.sopt.dosopttemplate.db.local.PreferenceManager
import org.sopt.dosopttemplate.db.remote.RetrofitManager.BASE_URL
import org.sopt.dosopttemplate.model.dto.RespResult
import org.sopt.dosopttemplate.model.dto.req.LoginReq
import org.sopt.dosopttemplate.model.dto.req.SignUpReq
import org.sopt.dosopttemplate.model.dto.resp.LoginResp
import org.sopt.dosopttemplate.model.dto.resp.SignUpResp
import org.sopt.dosopttemplate.model.dto.resp.auth.LoginResp
import org.sopt.dosopttemplate.model.dto.resp.auth.SignUpResp
import org.sopt.dosopttemplate.util.toErrorResult
import retrofit2.Call
import retrofit2.Response

class ApiHelper(private val retrofitService: RetrofitService) {
class AuthApiHelper(private val authAPI: AuthAPI) {
private val preferenceManager = PreferenceManager()

fun signUp(
Expand All @@ -20,7 +21,7 @@ class ApiHelper(private val retrofitService: RetrofitService) {
password: String,
onResponse: (SignUpResp) -> Unit
) {
retrofitService.signUp(SignUpReq(id, nickname, password))
authAPI.signUp(SignUpReq(id, nickname, password))
.enqueue(object : retrofit2.Callback<Unit> {
override fun onResponse(
call: Call<Unit>,
Expand All @@ -29,7 +30,7 @@ class ApiHelper(private val retrofitService: RetrofitService) {
if (response.isSuccessful && response.code() == 201) {
onResponse(SignUpResp.Success(response.headers()["Location"]?.split("/")?.last().toString()))
} else {
onResponse(SignUpResp.Error(response.errorBody()?.toErrorResult()?.message.toString()))
onResponse(SignUpResp.Error(response.errorBody()?.toErrorResult(BASE_URL)?.message.toString()))
}
}

Expand All @@ -40,7 +41,7 @@ class ApiHelper(private val retrofitService: RetrofitService) {
}

fun login(id: String, password: String, auto: Boolean, onResponse: (RespResult) -> Unit) {
retrofitService.login(LoginReq(id, password))
authAPI.login(LoginReq(id, password))
.enqueue(object : retrofit2.Callback<LoginResp> {
override fun onResponse(call: Call<LoginResp>, response: Response<LoginResp>) {
if (response.isSuccessful && response.code() == 200) {
Expand All @@ -53,7 +54,7 @@ class ApiHelper(private val retrofitService: RetrofitService) {
onResponse(it)
}
} else {
response.errorBody()?.toErrorResult()?.let {
response.errorBody()?.toErrorResult(BASE_URL)?.let {
onResponse(it)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.sopt.dosopttemplate.BuildConfig
import org.sopt.dosopttemplate.api.RetrofitService
import org.sopt.dosopttemplate.BuildConfig.BASE_URL
import org.sopt.dosopttemplate.BuildConfig.USER_BASE_URL
import org.sopt.dosopttemplate.api.AuthAPI
import org.sopt.dosopttemplate.api.UserAPI
import retrofit2.Retrofit

object RetrofitManager {
private const val BASE_URL = BuildConfig.BASE_URL
const val BASE_URL = BuildConfig.BASE_URL
const val USER_BASE_URL = BuildConfig.BASE_URL

private val httpLoggingInterceptor = HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)
Expand All @@ -20,17 +24,26 @@ object RetrofitManager {
.addInterceptor(httpLoggingInterceptor)
.build()

val retrofit: Retrofit by lazy{
fun getRetrofit(url: String): Retrofit =
Retrofit.Builder()
.baseUrl(url)
.client(okHttpClient)
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.build()

val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.build()
}

inline fun <reified T> create(): T = retrofit.create<T>(T::class.java)
// inline fun <reified T> create(): T = retrofit.create<T>(T::class.java)
inline fun <reified T, B> create(url: B): T = getRetrofit(url.toString()).create<T>(T::class.java)
}

object RetrofitServicePool {
val authService = RetrofitManager.create<RetrofitService>()
val authService = RetrofitManager.create<AuthAPI, String>(BASE_URL)
val userService = RetrofitManager.create<UserAPI, String>(USER_BASE_URL)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.sopt.dosopttemplate.db.remote

import android.util.Log
import org.sopt.dosopttemplate.api.AuthAPI
import org.sopt.dosopttemplate.api.UserAPI
import org.sopt.dosopttemplate.model.dto.resp.user.UserResp
import retrofit2.Call
import retrofit2.Response

class UserApiHelper(private val userAPI: UserAPI) {
fun getUserList(page: Int) {
userAPI.getUserList(page).enqueue(object: retrofit2.Callback<UserResp> {
override fun onResponse(call: Call<UserResp>, response: Response<UserResp>) {
if (response.isSuccessful && response.code() == 200) {
Log.e("로그", "${response.body()}")
} else {

}
}

override fun onFailure(call: Call<UserResp>, t: Throwable) {
t.printStackTrace()
}
})
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.sopt.dosopttemplate.model.dto.resp
package org.sopt.dosopttemplate.model.dto.resp.auth

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.sopt.dosopttemplate.model.dto.resp
package org.sopt.dosopttemplate.model.dto.resp.auth

sealed class SignUpResp {
data class Success(val location: String): SignUpResp()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.sopt.dosopttemplate.model.dto.resp.user

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class UserDataResp(
@SerialName("id")
val id: Int,
@SerialName("email")
val email: String,
@SerialName("first_name")
val first_name: String,
@SerialName("last_name")
val last_name: String,
@SerialName("avatar")
val avatar: String
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package org.sopt.dosopttemplate.model.dto.resp.user

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class UserResp(
@SerialName("page")
val page: Int,
@SerialName("per_page")
val per_page: Int,
@SerialName("total")
val total: Int,
@SerialName("total_pages")
val total_pages: Int,
@SerialName("data")
val data: List<UserDataResp>,
@SerialName("support")
val support: UserSupportResp
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package org.sopt.dosopttemplate.model.dto.resp.user

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class UserSupportResp(
@SerialName("url")
val url: String,
@SerialName("text")
val text: String,
)
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,41 @@ package org.sopt.dosopttemplate.presentation.home

import android.content.res.Configuration
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import org.sopt.dosopttemplate.DoSoptApp
import org.sopt.dosopttemplate.R
import org.sopt.dosopttemplate.base.BaseActivity
import org.sopt.dosopttemplate.databinding.ActivityHomeBinding
import org.sopt.dosopttemplate.model.HomeBottomItem
import org.sopt.dosopttemplate.model.HomeProfileModel
import org.sopt.dosopttemplate.presentation.home.viewmodel.HomeViewModel
import org.sopt.dosopttemplate.repository.UserRepository
import org.sopt.dosopttemplate.util.UserViewModelFactory
import org.sopt.dosopttemplate.util.sampleDeque
import org.sopt.dosopttemplate.util.showShortToastMessage
import org.sopt.dosopttemplate.util.toProfileBirth

class HomeActivity : BaseActivity<ActivityHomeBinding>(ActivityHomeBinding::inflate) {
private var backPressedTime = 0L
private val homeViewModel: HomeViewModel by viewModels()
private lateinit var homeViewModel: HomeViewModel
private var birthdayDeque = ArrayDeque<HomeProfileModel.ProfileBirthday>()
private var homeSampleDeque = sampleDeque.toMutableList()

override fun initView() {
initViewModel()
initList()
setBirthdayContent()
setHomeProfileList()
initFragment()
homeViewModel.getUserList()
}

private fun initViewModel() {
homeViewModel = ViewModelProvider(
this,
UserViewModelFactory(UserRepository(DoSoptApp.getUserApiHelperInstance()))
).get(HomeViewModel::class.java)
}

private fun initFragment() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import org.sopt.dosopttemplate.db.local.PreferenceManager.Companion.NICKNAME
class MyPageFragment : BaseFragment<FragmentMypageBinding>() {
override val layoutId: Int
get() = R.layout.fragment_mypage
private lateinit var preferenceManager: PreferenceManager

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@ package org.sopt.dosopttemplate.presentation.home.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.sopt.dosopttemplate.model.HomeBottomItem
import org.sopt.dosopttemplate.model.HomeProfileModel
import org.sopt.dosopttemplate.repository.UserRepository

class HomeViewModel : ViewModel() {
class HomeViewModel(
private val userRepository: UserRepository
) : ViewModel() {
private val _bottomItemId = MutableLiveData<HomeBottomItem>()
val bottomItemId: LiveData<HomeBottomItem> = _bottomItemId

Expand Down Expand Up @@ -55,4 +60,10 @@ class HomeViewModel : ViewModel() {
it.toList()
}
}

fun getUserList(page: Int = 1) {
viewModelScope.launch {
userRepository.getUserList(page)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package org.sopt.dosopttemplate.presentation.login
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.ViewModelProvider
import org.sopt.dosopttemplate.DoSoptApp
Expand All @@ -17,7 +16,7 @@ import org.sopt.dosopttemplate.db.local.PreferenceManager.Companion.ID
import org.sopt.dosopttemplate.db.local.PreferenceManager.Companion.MBTI
import org.sopt.dosopttemplate.db.local.PreferenceManager.Companion.PWD
import org.sopt.dosopttemplate.model.dto.RespResult
import org.sopt.dosopttemplate.model.dto.resp.LoginResp
import org.sopt.dosopttemplate.model.dto.resp.auth.LoginResp
import org.sopt.dosopttemplate.presentation.home.HomeActivity
import org.sopt.dosopttemplate.presentation.login.viewmodel.LoginViewModel
import org.sopt.dosopttemplate.presentation.signup.SignUpActivity
Expand All @@ -26,7 +25,6 @@ import org.sopt.dosopttemplate.util.AuthViewModelFactory
import org.sopt.dosopttemplate.util.hideKeyboard
import org.sopt.dosopttemplate.util.showShortSnackBar
import org.sopt.dosopttemplate.util.showShortToastMessage
import org.sopt.dosopttemplate.util.toMBTI

class LoginActivity : BaseActivity<ActivityLoginBinding>(ActivityLoginBinding::inflate) {
private lateinit var loginViewModel: LoginViewModel
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import org.sopt.dosopttemplate.R
import org.sopt.dosopttemplate.base.BaseActivity
import org.sopt.dosopttemplate.databinding.ActivitySignUpBinding
import org.sopt.dosopttemplate.db.local.PreferenceManager
import org.sopt.dosopttemplate.model.dto.resp.SignUpResp
import org.sopt.dosopttemplate.model.dto.resp.auth.SignUpResp
import org.sopt.dosopttemplate.presentation.signup.viewmodel.SignUpViewModel
import org.sopt.dosopttemplate.repository.AuthRepository
import org.sopt.dosopttemplate.util.AuthViewModelFactory
Expand Down
Loading

0 comments on commit 34eaa99

Please sign in to comment.