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

[리팩토링] Post, Service 코드 개선 및 테스트 코드 추가 #129

Open
wants to merge 9 commits into
base: develop
Choose a base branch
from
3 changes: 2 additions & 1 deletion src/main/java/com/yapp18/retrospect/config/ErrorInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ public enum ErrorInfo {
TEMPLATE_NULL("EE004", "존재하지 않는 템플릿입니다."),
TAG_NULL("EE005", "존재하지 않는 태그입니다."),
IMAGE_NULL("EE006", "존재하지 않는 이미지입니다."),
LIKE_NULL("EE007", "존재하지 않는 스크랩입니다.");
LIKE_NULL("EE007", "존재하지 않는 스크랩입니다."),
CONDITION_NULL("EE008","해당 조건에 맞는 회고글이 없습니다.");

private final String errorCode;
private final String errorMessage;
Expand Down
21 changes: 12 additions & 9 deletions src/main/java/com/yapp18/retrospect/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,25 +70,30 @@ public Post findByPostIdx(Long postIdx){
@Transactional(readOnly = true)
public ApiPagingResultResponse<PostDto.ListResponse> getPostsListView(Long cursorId, Pageable page, Long userIdx){
// 마지막으로 검색된 회고글의 조회수
List<PostDto.ListResponse> result = getPostsView(cursorId, page).stream().map(post->postMapper.postToListResponse(post, userIdx))
List<Post> posts = getPostsView(cursorId, page);
if (posts.isEmpty()) throw new EntityNullException(ErrorInfo.CONDITION_NULL);
Copy link
Contributor

Choose a reason for hiding this comment

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

회고글 존재하지 않을 땐 예외 날리는 것보단 빈 배열 200으로 응답하는게 낫지 않을까?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

그 두 개 방법이랑 고민해봤는데

  • return 값이 현재 postDto.ListResponse
  • mapstruct로 바꾸려면 배열에 값이 필요함
    등등의 이유로 일단 exception 처리는 해놨는데, ApiPagingResult가 Controller 쪽으로 빼서 변환하기 어렵더라구 함 다시 시도해볼게!

Copy link
Contributor

Choose a reason for hiding this comment

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

CommentController.getCommentsByPostIdx 한번 보는거 추천~


List<PostDto.ListResponse> result = posts.stream().map(post->postMapper.postToListResponse(post, userIdx))
.collect(Collectors.toList());
Long lastIdx = result.isEmpty() ? null : result.get(result.size()-1).getPostIdx(); // 다음 postIdx
return new ApiPagingResultResponse<>(isNextView(lastIdx), result);
}


// 최신순
@Transactional(readOnly = true)
public ApiPagingResultResponse<PostDto.ListResponse> getPostsListCreatedAt(Long cursorIdx, Long userIdx, Pageable pageable){
User user = userRepository.findByUserIdx(userIdx)
.orElseThrow(() -> new EntityNullException(ErrorInfo.USER_NULL));

List<Post> postList = cursorIdx == 0 || cursorIdx == null ?
List<Post> posts = cursorIdx == 0 || cursorIdx == null ?
postRepository.findByUserOrderByCreatedAtDesc(user, pageable)
: postRepository.cursorFindByUserOrderByCreatedAtDesc(cursorIdx, user.getUserIdx(), pageable);
if (posts.isEmpty()) throw new EntityNullException(ErrorInfo.CONDITION_NULL);

Long lastIdx = postList.isEmpty() ? null : postList.get(postList.size() - 1).getPostIdx(); // 낮은 조회수 체크
Long lastIdx = posts.isEmpty() ? null : posts.get(posts.size() - 1).getPostIdx(); // 낮은 조회수 체크

List<PostDto.ListResponse> result = postList.stream()
List<PostDto.ListResponse> result = posts.stream()
.map(post -> postMapper.postToListResponse(post, userIdx))
.collect(Collectors.toList());

Expand All @@ -101,7 +106,9 @@ public ApiPagingResultResponse<PostDto.ListResponse> getPostsListCreatedAt(Long
public ApiIsResultResponse<PostDto.detailResponse> findPostContents(Long postIdx, Long userIdx){
Post post = postRepository.findById(postIdx)
.orElseThrow(() -> new EntityNullException(ErrorInfo.POST_NULL));
post.updateview(post.getView()); // 조회수 증가
// 조회수 증가
post.updateview(post.getView());

if(userIdx != 0L){
listService.saveRecentReadPosts(userIdx, postIdx); // 최근 읽은 글에 추가
}
Expand Down Expand Up @@ -181,10 +188,6 @@ public boolean deletePosts(Long userIdx,Long postIdx) {
.orElseThrow(() -> new EntityNullException(ErrorInfo.POST_NULL));
if (isWriter(post.getUser().getUserIdx(), userIdx)){
postRepository.deleteById(postIdx);
// if (listService.isPostsExist(userIdx, postIdx)) {
// // ** redis에 있는 모든...어쩌구....
// listService.deleteRedisPost(userIdx, postIdx); // redis 에서도 삭제
// }
return true;
}
return false;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.yapp18.retrospect.web.advice;

import com.yapp18.retrospect.web.dto.ApiDefaultResponse;
import com.yapp18.retrospect.web.dto.ErrorDefaultResponse;
import com.yapp18.retrospect.web.dto.ErrorDto;
import org.springframework.http.HttpStatus;
Expand Down Expand Up @@ -79,7 +80,7 @@ public ResponseEntity<Map<String, Object>> restExceptionHandler(RestException e)

// @ExceptionHandler(EntityNullException.class)
// public ResponseEntity<Object> entityNullExceptionHandler(EntityNullException e) {
// return new ResponseEntity<>(ApiDefaultResponse.res(404, e.getMessage()), e.getStatus());
// return new ResponseEntity<>(ApiDefaultResponse.res(404, e.getMessage()), e.getCode());
// }

// @ResponseStatus(HttpStatus.BAD_REQUEST)
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/application-key.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
secret:
access: accessTokenSecret
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.yapp18.retrospect.post;

public class PostControllerTest {
}
66 changes: 0 additions & 66 deletions src/test/java/com/yapp18/retrospect/post/PostCrudTest.java

This file was deleted.

71 changes: 71 additions & 0 deletions src/test/java/com/yapp18/retrospect/post/PostServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.yapp18.retrospect.post;

import com.yapp18.retrospect.common.EntityCreator;
import com.yapp18.retrospect.domain.post.Post;
import com.yapp18.retrospect.domain.post.PostQueryRepository;
import com.yapp18.retrospect.domain.post.PostRepository;
import com.yapp18.retrospect.domain.template.Template;
import com.yapp18.retrospect.domain.template.TemplateRepository;
import com.yapp18.retrospect.domain.user.Role;
import com.yapp18.retrospect.domain.user.User;
import com.yapp18.retrospect.domain.user.UserRepository;
import com.yapp18.retrospect.security.oauth2.AuthProvider;
import com.yapp18.retrospect.service.PostService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.PageRequest;

import java.awt.font.OpenType;
import java.util.List;
import java.util.Optional;

//@DataJpaTest
@ExtendWith(MockitoExtension.class)
public class PostServiceTest {

@InjectMocks
private PostService postService;

@Mock
private PostRepository postRepository;
@Mock
private UserRepository userRepository;
@Mock
private TemplateRepository templateRepository;

@BeforeEach
void setUp(){
// // user 설정
// User user1 = User.builder()
// .name("허정민").nickname("tape22").intro("자기소개.").job("백수")
// .email("[email protected]").profile("profile_url")
// .provider(AuthProvider.google).providerId("13453252535").role(Role.MEMBER).build();
// // template 설정
// Template template = Template.builder().template("템플릿").templateName("4F").build();
//
// userRepository.save(user1);
// templateRepository.save(template);
//
// System.out.println(user1.getUserIdx());
// System.out.println(template.getTemplateIdx());
}

@Test
void 회고글이_없는_경우(){
// list로 글 읽어오기
List<Post> posts = postRepository.findAllByOrderByViewDesc(PageRequest.of(0,10));
System.out.println(posts);

// when

// 없으면 빈 배열? 아니면 exception?

}
}