Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/#19: week7 compose 과제 구현 #20

Open
wants to merge 27 commits into
base: develop-compose
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
a6263c4
chore/#11: 인터넷 권한 추가
youjin09222 May 3, 2024
ee48933
chore/#11: 라이브러리 추가 및 BASE_URL 숨기기
youjin09222 May 3, 2024
991c7e0
add/#11: Dto 추가
youjin09222 May 3, 2024
415a9f8
add/#11: AuthService 추가
youjin09222 May 3, 2024
ce8733d
add/#11: UserService 추가
youjin09222 May 3, 2024
6f175a6
add/#11: UserData 추가
youjin09222 May 3, 2024
6ab7a9e
mod/#11: Friend data 변경
youjin09222 May 3, 2024
230598d
feat/#11: UserPreference 추가
youjin09222 May 3, 2024
f51e011
feat/#11: ApiFactory 추가
youjin09222 May 3, 2024
47c12ff
feat/#11: 회원가입 서버 통신
youjin09222 May 3, 2024
1938b2e
feat/#11: 로그인 서버 통신
youjin09222 May 3, 2024
18d2d22
feat/#11: 회원 정보 조회
youjin09222 May 3, 2024
012559a
feat/#11: 회원 정보 적용
youjin09222 May 3, 2024
3846b36
refactor/#11: Application Context 사용하여 SharedPreferences 초기화
youjin09222 May 11, 2024
9223db8
refactor/#11: shared preferences의 edit 사용
youjin09222 May 11, 2024
3c28258
refactor/#11: shared preferences 상수 사용
youjin09222 May 11, 2024
a998575
refactor/#11: @Serializable로 변경
youjin09222 May 11, 2024
5bdae0e
refactor/#11: LocalContext.current 사용
youjin09222 May 11, 2024
bd73dad
refactor/#11: isInitialized로 초기화 확인
youjin09222 May 11, 2024
d23af01
#15 [FEAT] AUTH_BASE_URL 네이밍 변경
youjin09222 May 24, 2024
5991e25
Merge pull request #16 from NOW-SOPT-ANDROID/feat/week6_compose
youjin09222 Jun 6, 2024
5bcf94e
FEAT/#19: SignUpRepository 구현
youjin09222 Jun 7, 2024
c0efb02
REFACTOR/#19: SignUpViewModel에서 SignUpRepository 사용
youjin09222 Jun 7, 2024
02d5575
FEAT/#19: LoginRepository 구현
youjin09222 Jun 7, 2024
544dc83
REFACTOR/#19: LoginViewModel에서 LoginRepository 사용
youjin09222 Jun 7, 2024
13ea9e4
FEAT/#19: UserProfileRepository 구현
youjin09222 Jun 7, 2024
f63ae10
REFACTOR/#19: UserProfileViewModel에서 UserProfileRepository 사용
youjin09222 Jun 7, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'org.jetbrains.kotlin.plugin.serialization' version '1.9.0'
id 'kotlin-parcelize'
}

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

android {
namespace 'com.sopt.now.compose'
compileSdk 34
Expand All @@ -15,6 +20,8 @@ android {
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
buildConfigField "String", "AUTH_BASE_URL", properties["auth.base.url"]

vectorDrawables {
useSupportLibrary true
}
Expand All @@ -36,6 +43,7 @@ android {
buildFeatures {
compose true
viewBinding true
buildConfig true
}
composeOptions {
kotlinCompilerExtensionVersion '1.5.1'
Expand Down Expand Up @@ -69,4 +77,24 @@ dependencies {
androidTestImplementation 'androidx.compose.ui:ui-test-junit4'
debugImplementation 'androidx.compose.ui:ui-tooling'
debugImplementation 'androidx.compose.ui:ui-test-manifest'

//Gson
implementation "com.google.code.gson:gson:2.8.9"

// Glide
implementation("com.github.bumptech.glide:compose:1.0.0-beta01")

// retrofit2
implementation("com.squareup.retrofit2:retrofit:2.11.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
implementation("com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0")
implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.4.0")

// define a BOM and its version
implementation(platform("com.squareup.okhttp3:okhttp-bom:4.10.0"))
implementation ("androidx.compose.runtime:runtime-livedata:1.0.5")

// define any required OkHttp artifacts without version
implementation("com.squareup.okhttp3:okhttp")
implementation("com.squareup.okhttp3:logging-interceptor")
}
9 changes: 6 additions & 3 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
Expand All @@ -11,16 +13,17 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.NOWSOPTAndroid"
android:usesCleartextTraffic="true"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:name=".presentation.MainActivity"
android:exported="false"/>

<activity
android:name=".SignUpActivity"
android:name=".presentation.SignUpActivity"
android:exported="false"/>

<activity android:name=".LoginActivity"
<activity android:name=".presentation.LoginActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.NOWSOPTAndroid">
Expand Down
57 changes: 57 additions & 0 deletions app/src/main/java/com/sopt/now/compose/data/ApiFactory.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.sopt.now.compose.data

import android.util.Log
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
lateinit var userPreference: UserPreference
var isInitialized = false
private set

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 <reified T> create(): T = retrofit.create(T::class.java)
}

object ServicePool {
val authService = ApiFactory.create<AuthService>()
val userService = ApiFactory.create<UserService>()
}
20 changes: 20 additions & 0 deletions app/src/main/java/com/sopt/now/compose/data/AuthService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.sopt.now.compose.data

import com.sopt.now.compose.data.dto.request.RequestLoginDto
import com.sopt.now.compose.data.dto.request.RequestSignUpDto
import com.sopt.now.compose.data.dto.response.ResponseAuthDto
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST

interface AuthService {
@POST("member/join")
fun signUp(
@Body request: RequestSignUpDto,
): Call<ResponseAuthDto>

@POST("member/login")
fun login(
@Body request: RequestLoginDto,
): Call<ResponseAuthDto>
}
12 changes: 12 additions & 0 deletions app/src/main/java/com/sopt/now/compose/data/BaseState.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.sopt.now.compose.data

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

@Serializable
data class BaseState(
@SerialName("isSuccess")
val isSuccess: Boolean,
@SerialName("message")
val message: String
)
14 changes: 14 additions & 0 deletions app/src/main/java/com/sopt/now/compose/data/Friend.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.sopt.now.compose.data

import androidx.annotation.DrawableRes

data class Friend(
@DrawableRes val profileImage: Int,
val name: String,
val phone: String,
) {
companion object {
const val TYPE_USER = 0
const val TYPE_FRIEND = 1
}
}
55 changes: 55 additions & 0 deletions app/src/main/java/com/sopt/now/compose/data/UserPreference.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.sopt.now.compose.data

import android.content.Context

import androidx.core.content.edit
import com.sopt.now.compose.data.UserPreference.UserPreferenceKeys.KEY_USER_ID
import com.sopt.now.compose.data.UserPreference.UserPreferenceKeys.KEY_USER_NAME
import com.sopt.now.compose.data.UserPreference.UserPreferenceKeys.KEY_USER_PHONE
import com.sopt.now.compose.data.UserPreference.UserPreferenceKeys.PREF_USER_DATA

class UserPreference(context: Context) {
private val sharedPreferences = context.applicationContext.getSharedPreferences(PREF_USER_DATA, Context.MODE_PRIVATE)

// 사용자 아이디 저장
fun saveUserId(userId: String) {
sharedPreferences.edit {
putString(KEY_USER_ID, userId)
}
}

// 사용자 아이디 가져오기
fun getUserId(): String? {
return sharedPreferences.getString(KEY_USER_ID, null)
}

// 사용자 데이터 저장
fun saveUserData(userData: UserData) {
sharedPreferences.edit {
putString(KEY_USER_ID, userData.userId)
putString(KEY_USER_NAME, userData.userName)
putString(KEY_USER_PHONE, userData.userPhone)
}
}

// 사용자 데이터 가져오기
fun getUserData(): UserData? {
with(sharedPreferences){
val userId = getString("userId", null)
val userName = getString("userName", null)
val userPhone = getString("userPhone", null)

return if (userId != null && userName != null && userPhone != null) {
UserData(userId, userName, userPhone)
} else {
null
}
}
}
object UserPreferenceKeys {
const val PREF_USER_DATA = "userData"
const val KEY_USER_ID = "userId"
const val KEY_USER_NAME = "userName"
const val KEY_USER_PHONE = "userPhone"
}
}
11 changes: 11 additions & 0 deletions app/src/main/java/com/sopt/now/compose/data/UserService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.sopt.now.compose.data

import com.sopt.now.compose.data.dto.response.ResponseUserInfoDto
import retrofit2.Call
import retrofit2.http.GET

interface UserService {
@GET("member/info")
fun userInfo(
): Call<ResponseUserInfoDto>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.sopt.now.compose.data.dto.request

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

@Serializable
data class RequestLoginDto(
@SerialName("authenticationId")
val authenticationId: String,
@SerialName("password")
val password: String
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.sopt.now.compose.data.dto.request

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

@Serializable
data class RequestSignUpDto(
@SerialName("authenticationId")
val authenticationId: String,
@SerialName("password")
val password: String,
@SerialName("nickname")
val nickname: String,
@SerialName("phone")
val phone: String,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.sopt.now.compose.data.dto.response

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

@Serializable
data class ResponseAuthDto(
@SerialName("code")
val code: Int,
@SerialName("message")
val message: String,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.sopt.now.compose.data.dto.response

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

@Serializable
data class ResponseUserInfoDto(
@SerialName("code")
val code: Int,
@SerialName("message")
val message: String,
@SerialName("data")
val data: UserInfo
)

@Serializable
data class UserInfo(
@SerialName("authenticationId")
val authenticationId: String,
@SerialName("nickname")
val nickname: String,
@SerialName("phone")
val phone: String
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.sopt.now.compose.data.repository

import com.sopt.now.compose.core.view.UiState
import com.sopt.now.compose.data.ApiFactory
import com.sopt.now.compose.data.ServicePool.authService
import com.sopt.now.compose.data.dto.request.RequestLoginDto
import com.sopt.now.compose.data.dto.response.ResponseAuthDto
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class LoginRepository {
suspend fun postLogin(request: RequestLoginDto): UiState<ResponseAuthDto> {
return withContext(Dispatchers.IO) {
runCatching {
authService.postLogin(request)
}.fold(
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 fold는 처음 보는데요? runCatching은 onSuccess/onFailure만 알고있었는데 이런 방법도 있군요!

{ response ->
val userId = response.headers()["location"]
if (userId != null) {
ApiFactory.userPreference.saveUserId(userId)
}
UiState.Success(
response.body() ?: ResponseAuthDto(
-1,
"Empty response body"
)
)
},
{ UiState.Failure(it.message.toString()) }
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.sopt.now.compose.data.repository

import com.sopt.now.compose.core.view.UiState
import com.sopt.now.compose.data.ServicePool
import com.sopt.now.compose.data.dto.request.RequestSignUpDto
import com.sopt.now.compose.data.dto.response.ResponseAuthDto
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class SignUpRepository {
suspend fun postSignUp(requestSignUp: RequestSignUpDto): UiState<ResponseAuthDto> {
return withContext(Dispatchers.IO) {
runCatching {
ServicePool.authService.postSignUp(requestSignUp)
}.fold(
{ UiState.Success(it) },
{ UiState.Failure(it.message.toString()) }
)
}
}
}
Loading