Skip to content

Commit

Permalink
KKUMI-108 [FEAT] #90 - 포스트 삭제 후 Refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
jung0115 committed Oct 16, 2024
1 parent cf3bad8 commit a8bd927
Show file tree
Hide file tree
Showing 9 changed files with 102 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.marastro.mykkumi.common_ui.base

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
Expand All @@ -9,6 +10,7 @@ import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.google.android.material.internal.ViewUtils.hideKeyboard

abstract class BaseFragment<T: ViewDataBinding>(
@LayoutRes private val layoutId: Int
Expand Down Expand Up @@ -39,8 +41,11 @@ abstract class BaseFragment<T: ViewDataBinding>(
binding.apply(block)
}

@SuppressLint("RestrictedApi")
override fun onDestroyView() {
view?.let { hideKeyboard(it) }
_binding = null
super.onDestroyView()

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ package com.marastro.mykkumi.data.datasource
import com.marastro.mykkumi.data.dto.request.PostEditRequestDTO
import com.marastro.mykkumi.data.dto.response.HomePostListDTO
import com.marastro.mykkumi.data.dto.response.PostEditResponseDTO
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query

interface PostDataSource {
Expand All @@ -19,4 +22,9 @@ interface PostDataSource {
suspend fun uploadPost(
@Body params: PostEditRequestDTO
) : PostEditResponseDTO

@DELETE("/api/v1/posts/{postId}")
suspend fun deletePost(
@Path("postId") postId: Int
) : Response<Void?>?
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.marastro.mykkumi.data.repository

import com.google.gson.Gson
import com.marastro.mykkumi.data.datasource.PostDataSource
import com.marastro.mykkumi.data.dto.request.PostEditRequestDTO
import com.marastro.mykkumi.data.dto.request.PostImageRequestDTO
Expand All @@ -8,13 +9,22 @@ import com.marastro.mykkumi.data.dto.request.PostProductRequestDTO
import com.marastro.mykkumi.domain.entity.HomePostListVO
import com.marastro.mykkumi.domain.entity.PostEditResponseVO
import com.marastro.mykkumi.domain.entity.PostImageVO
import com.marastro.mykkumi.domain.exception.ApiException
import com.marastro.mykkumi.domain.exception.ErrorResponse
import com.marastro.mykkumi.domain.repository.PostRepository
import retrofit2.HttpException
import javax.inject.Inject

class PostRepositoryImpl @Inject constructor(
private val postDataSource: PostDataSource
) : PostRepository {

private companion object {
private const val INVALID_TOKEN = "INVALID_TOKEN"
private const val INVALID_VALUE = "INVALID_VALUE"
private const val ACCESS_DENIED = "ACCESS_DENIED"
}

override suspend fun getHomePostList(cursor: String?, limit: Int?): HomePostListVO {
return postDataSource.getHomePostList(cursor, limit).toEntity()
}
Expand Down Expand Up @@ -43,4 +53,26 @@ class PostRepositoryImpl @Inject constructor(
)
).toEntity()
}

override suspend fun deletePost(postId: Int) : Boolean {
try {
postDataSource.deletePost(postId)

return true
} catch (e: HttpException) {
handleApiException(e)
}
}

private fun handleApiException(exception: HttpException): Nothing {
val errorBody = exception.response()?.errorBody()?.string()
val errorResponse = Gson().fromJson(errorBody, ErrorResponse::class.java)

when (errorResponse.errorCode) {
INVALID_TOKEN -> throw ApiException.InvalidTokenException() // 만료된 토큰
INVALID_VALUE -> throw ApiException.InvalidPostValue(errorResponse.message) // 존재하지 않는 게시물
ACCESS_DENIED -> throw ApiException.AccessDeniedUserForPost(errorResponse.message) // 삭제 권한 없음
else -> throw ApiException.UnknownApiException("An unknown error occurred: ${errorResponse.message}")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package com.marastro.mykkumi.domain.exception
sealed class ApiException(message: String) : Exception(message) {
class InvalidTokenException : ApiException("Invalid token. Please log in again.")
class DuplicateValueException(message: String) : ApiException(message)
class AccessDeniedUserForPost(message: String): ApiException(message)
class InvalidNickNameValue(message: String): ApiException(message)
class InvalidPostValue(message: String): ApiException(message)
class InvalidRefreshTokenException : ApiException("장시간 접속하지 않아 로그아웃 되었습니다.")
class DuplicateReportException(message: String) : ApiException(message)
class NotFoundException(message: String) : ApiException(message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ import com.marastro.mykkumi.domain.entity.PostImageVO
interface PostRepository {
suspend fun getHomePostList(cursor: String?, limit: Int?): HomePostListVO
suspend fun uploadPost(subCategory: Long, content: String?, postImages: MutableList<PostImageVO>): PostEditResponseVO
suspend fun deletePost(postId: Int) : Boolean
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.marastro.mykkumi.domain.usecase.post

import com.marastro.mykkumi.domain.repository.PostRepository
import javax.inject.Inject

class DeletePostUseCase @Inject constructor(
private val repository: PostRepository
) {
suspend operator fun invoke(postId: Int): Boolean {
return repository.deletePost(postId)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(R.layout.fragment_home),
binding.swipeRefreshLayout.isRefreshing = false
}

// 포스트 삭제됨 -> 새로 고침
viewModel.isDeletePostDone.observe(viewLifecycleOwner, Observer { isDeletePostDone ->
if(isDeletePostDone) {
onResume()
viewModel.doneResume()
}
})

// 포스트 리스트 추가
viewModel.postCursor.observe(viewLifecycleOwner, Observer {
if(postListAdapter.postList.size != viewModel.postListUiState.value.size) {
Expand Down Expand Up @@ -325,7 +333,12 @@ class HomeFragment : BaseFragment<FragmentHomeBinding>(R.layout.fragment_home),
fun deletePostDialog(postId: Int) {
val dialog = PostDeleteConfirmDialog(this)
dialog.setOnClickListener { postId ->
Log.d("test", "${postId} 게시물 삭제")
viewModel.deletePost(
postId = postId,
showToast = {
showToast(it)
}
)
}
dialog.show(postId)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import com.marastro.mykkumi.domain.usecase.post.GetHomePostListUseCase
import com.marastro.mykkumi.domain.usecase.report.ReportPostUseCase
import com.marastro.mykkumi.domain.usecase.report.ReportUserUseCase
import com.marastro.mykkumi.common_ui.post.ViewProductInfoBottomSheet
import com.marastro.mykkumi.domain.usecase.post.DeletePostUseCase
import com.marastro.mykkumi.feature.home.report.ChooseReportBottomSheet
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
Expand All @@ -33,6 +34,7 @@ import javax.inject.Inject
class HomeViewModel @Inject constructor(
private val getBannerListUseCase: GetBannerListUseCase,
private val getHomePostListUseCase: GetHomePostListUseCase,
private val deletePostUseCase: DeletePostUseCase,
private val authTokenDataStore: AuthTokenDataStore,
private val reportPostUseCase: ReportPostUseCase,
private val reportUserUseCase: ReportUserUseCase,
Expand Down Expand Up @@ -66,6 +68,9 @@ class HomeViewModel @Inject constructor(
private var _userNickname = MutableStateFlow<String>("")
val userNickname: StateFlow<String> get() = _userNickname

private var _isDeletePostDone = MutableLiveData<Boolean>(false)
val isDeletePostDone: LiveData<Boolean> get() = _isDeletePostDone

// 유저 정보 세팅
fun initUserInfo() {
_userNickname.value = authTokenDataStore.getUserNickname() ?: ""
Expand All @@ -89,8 +94,6 @@ class HomeViewModel @Inject constructor(
_bannerListUiState.emit( mutableListOf() )
}
}


}

// 홈 > 배너 캐러셀에서 배너 선택
Expand Down Expand Up @@ -205,4 +208,27 @@ class HomeViewModel @Inject constructor(
bottomSheet.arguments = bundle
bottomSheet.show(fragment.parentFragmentManager, bottomSheet.tag)
}

// 포스트 삭제
fun deletePost(
postId: Int,
showToast: (message: String) -> Unit
) {
viewModelScope.launch {
try {
deletePostUseCase(postId)

showToast("게시물이 삭제되었습니다")
_isDeletePostDone.setValue(true)
} catch (e: ApiException.AccessDeniedUserForPost) {
e.message?.let { showToast(it) }
} catch (e: ApiException.InvalidPostValue) {
e.message?.let { showToast(it) }
}
}
}

fun doneResume() {
_isDeletePostDone.setValue(false)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,6 @@ class PostListAdapter (

// 로그인 했을 때
if(viewModel.isLogined.value) {
Log.d("test", "${item.writer.nickname}, ${userNickname}")
// 내가 쓴 글일 때
if(item.writer.nickname == userNickname) {
binding.includePostWriter.btnFollow.visibility = View.GONE // 팔로우 숨기기
Expand Down

0 comments on commit a8bd927

Please sign in to comment.