Skip to content

Commit

Permalink
Merge pull request #192 from Funssion-SWM/qna
Browse files Browse the repository at this point in the history
fix: 질문이 달린 메모를 삭제시 질문조회시 메모 id가 없어서 발생하는 오류 해결
  • Loading branch information
goathoon authored Nov 18, 2023
2 parents 92ac09d + 9a4926b commit a5405ab
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public DeleteFailException(String message) {
super(DEFAULT_MESSAGE + message, new ErrorResult(HttpStatus.INTERNAL_SERVER_ERROR, message));
}


public DeleteFailException(String message, Throwable cause) {
super(DEFAULT_MESSAGE + message, new ErrorResult(HttpStatus.INTERNAL_SERVER_ERROR, message), cause);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import Funssion.Inforum.common.exception.etc.UnAuthorizedException;
import Funssion.Inforum.common.exception.forbidden.ForbiddenException;
import Funssion.Inforum.common.utils.SecurityContextUtils;
import Funssion.Inforum.domain.employer.domain.EmployeeWithStatus;
import Funssion.Inforum.domain.employer.repository.EmployerRepository;
import Funssion.Inforum.domain.follow.repository.FollowRepository;
import Funssion.Inforum.domain.member.entity.MemberProfileEntity;
Expand All @@ -19,8 +18,8 @@
import Funssion.Inforum.domain.post.memo.dto.response.MemoDto;
import Funssion.Inforum.domain.post.memo.dto.response.MemoListDto;
import Funssion.Inforum.domain.post.memo.repository.MemoRepository;
import Funssion.Inforum.domain.post.qna.repository.QuestionRepository;
import Funssion.Inforum.domain.post.utils.AuthUtils;
import Funssion.Inforum.domain.score.repository.ScoreRepository;
import Funssion.Inforum.domain.score.service.ScoreService;
import Funssion.Inforum.domain.tag.repository.TagRepository;
import Funssion.Inforum.s3.S3Repository;
Expand Down Expand Up @@ -64,6 +63,7 @@ public class MemoService {
private final FollowRepository followRepository;
private final NotificationRepository notificationRepository;
private final EmployerRepository employerRepository;
private final QuestionRepository questionRepository;

public List<MemoListDto> getMemosForMainPage(DateType period, OrderType orderBy, Long pageNum, Long resultCntPerPage) {

Expand Down Expand Up @@ -256,6 +256,7 @@ public void deleteMemo(Long memoId) {
Memo willBeDeletedMemo = memoRepository.findById(memoId);

checkPermission(userId, willBeDeletedMemo);
checkMemoHasQuestionThenCanNotBeDeleted(memoId);
checkDeletableInSeries(willBeDeletedMemo.getSeriesId());

try {
Expand All @@ -274,6 +275,10 @@ public void deleteMemo(Long memoId) {
}
}

private void checkMemoHasQuestionThenCanNotBeDeleted(Long memoId) {
if (questionRepository.getQuestionIdByMemoId(memoId).isPresent()) throw new CannotDeleteMemoException("질문이 달린 메모는 삭제할 수 없습니다.");
}

private void checkDeletableInSeries(Long seriesId) {
if (Objects.nonNull(seriesId) && memoRepository.findAllBySeriesId(seriesId).size() <= 2)
throw new BadRequestException("속한 시리즈의 남은 메모가 2개 이하가 되어 삭제할 수 없습니다. 시리즈를 먼저 삭제해주세요.");
Expand Down Expand Up @@ -327,4 +332,10 @@ private List<MemoListDto> getMemoListDtosSearchedByTag(String searchString, Long
.toList();
}

public class CannotDeleteMemoException extends BadRequestException{

public CannotDeleteMemoException(String message) {
super(message);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ public IsSuccessResponseDto deleteQuestion(@PathVariable(value="id") Long questi
return questionService.deleteQuestion(questionId,authorId);
}


@GetMapping
public List<Question> getQuestions(
@RequestParam (required = false, defaultValue = "NEW") OrderType orderBy,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import Funssion.Inforum.domain.post.qna.dto.request.QuestionSaveDto;

import java.util.List;
import java.util.OptionalLong;

public interface QuestionRepository {
Question createQuestion(Question question);
Expand Down Expand Up @@ -36,4 +37,6 @@ public interface QuestionRepository {
List<Question> getQuestionsOfMyAnswer(Long userId, Long pageNum, Long resultCntPerPage);

List<Question> getQuestionsOfMyLikedAnswer(Long userId, Long pageNum, Long resultCntPerPage);

OptionalLong getQuestionIdByMemoId(Long memoId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalLong;

@Repository
public class QuestionRepositoryImpl implements QuestionRepository {
Expand Down Expand Up @@ -162,6 +163,19 @@ public List<Question> getQuestionsOfMyLikedAnswer(Long userId, Long pageNum, Lon
return template.query(sql,questionRowMapper(),userId, resultCntPerPage, resultCntPerPage*pageNum);
}

@Override
public OptionalLong getQuestionIdByMemoId(Long memoId) {
String sql =
"SELECT id " +
"FROM post.question " +
"WHERE memo_id = ?";
try {
return OptionalLong.of(template.queryForObject(sql, Long.class,memoId));
}catch(EmptyResultDataAccessException e){
return OptionalLong.empty();
}
}

@Override
public Question getOneQuestion(Long questionId) {
String sql = "select id, author_id, author_name, author_image_path, author_rank, title, text, description, likes, is_solved, created_date, updated_date, tags, replies_count, answers, is_solved, memo_id " +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,13 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.http.MediaType.*;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(MemoController.class)
class MemoControllerTest {
Expand Down Expand Up @@ -215,6 +214,7 @@ void removeMemo() throws Exception {
.andExpect(status().isBadRequest());
}


@Test
@WithMockUser
@DisplayName("메모 검색하기")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import Funssion.Inforum.domain.post.memo.dto.response.MemoDto;
import Funssion.Inforum.domain.post.memo.dto.response.MemoListDto;
import Funssion.Inforum.domain.post.memo.repository.MemoRepository;
import Funssion.Inforum.domain.post.qna.repository.QuestionRepository;
import Funssion.Inforum.domain.post.utils.AuthUtils;
import Funssion.Inforum.domain.score.repository.ScoreRepository;
import Funssion.Inforum.domain.score.service.ScoreService;
Expand All @@ -33,6 +34,7 @@
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.OptionalLong;

import static Funssion.Inforum.common.constant.CRUDType.READ;
import static Funssion.Inforum.common.constant.DateType.*;
Expand All @@ -50,6 +52,8 @@ public class MemoServiceTest {
@Mock MyRepository myRepository;
@Mock
EmployerRepository employerRepository;
@Mock
QuestionRepository questionRepository;
@Mock S3Repository s3Repository;
@Mock
ScoreRepository scoreRepository;
Expand Down Expand Up @@ -627,6 +631,18 @@ void deleteMemoWithLoginArrayEx() throws SQLException {
assertThatThrownBy(() -> memoService.deleteMemo(memoID1))
.isInstanceOf(ArrayToListException.class);
}
@Test
@DisplayName("질문이 달린 메모는 삭제할 수 없다.")
void cannotDeleteMemoWhenQuestionAdded(){
Long questionId = 1L;
given(AuthUtils.getUserId(AdditionalMatchers.not(eq(READ))))
.willReturn(userID1);
given(memoRepository.findById(memoID1))
.willReturn(memo1);
given(questionRepository.getQuestionIdByMemoId(memoID1)).willReturn(OptionalLong.of(questionId));
assertThatThrownBy(()-> memoService.deleteMemo(memoID1))
.isExactlyInstanceOf(MemoService.CannotDeleteMemoException.class);
}

@Test
@DisplayName("로그인 후 임시 메모 삭제 성공 케이스")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package Funssion.Inforum.domain.post.qna.repository;

import Funssion.Inforum.domain.post.qna.domain.Question;
import Funssion.Inforum.domain.score.Rank;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
@Transactional
public class QuestionRepositoryTest {
@Autowired
QuestionRepository questionRepository;

Question memoQuestion;
Long targetMemoId = 1L;
Long memoIdWhichDoNotHaveQuestion = 2L;
@BeforeEach
void init(){
memoQuestion = questionRepository.createQuestion(Question.builder()
.authorId(1L)
.authorName("test")
.authorImagePath("test")
.title("java")
.text("{\"content\":\"java is good?\"}")
.description("java is ...")
.tags(Collections.emptyList())
.memoId(targetMemoId)
.rank(Rank.BRONZE_5.toString())
.build());
}

@Test
@DisplayName("메모와 연관된 질문인지 아닌지 확인합니다")
void isMemoQuestionOrNot(){
assertThat(questionRepository.getQuestionIdByMemoId(targetMemoId).isPresent()).isEqualTo(true);
assertThat(questionRepository.getQuestionIdByMemoId(memoIdWhichDoNotHaveQuestion).isEmpty()).isEqualTo(true);

}
}

0 comments on commit a5405ab

Please sign in to comment.