Skip to content

Commit

Permalink
Merge branch 'develop' into feat#195
Browse files Browse the repository at this point in the history
  • Loading branch information
MinYeongPark authored Jun 2, 2024
2 parents 72bb583 + 6276b3b commit c6c771c
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 8 deletions.
35 changes: 35 additions & 0 deletions src/main/java/friend/spring/converter/PostConverter.java
Original file line number Diff line number Diff line change
Expand Up @@ -1012,6 +1012,41 @@ public static PostResponseDTO.PostReportRes toPostReportRes(PostResponseDTO.Repo
.build();
}

public static PostResponseDTO.PostSearchRes PostSearchResDTO(Post post,Long userId) {
Integer likeCount = post.getPostLikeList().size();
Integer commentCount = post.getCommentList().size();
Boolean isLike = !post.getPostLikeList().stream().filter(like -> like.getUser().getId().equals(userId)).collect(Collectors.toList()).isEmpty();
Boolean isComment = !post.getCommentList().stream().filter(like -> like.getUser().getId().equals(userId)).collect(Collectors.toList()).isEmpty();
File userFile = null;
String userImg = null;
Optional<File> userFileOptional = Optional.ofNullable(post.getUser().getFile());

if (userFileOptional.isPresent()) {
userFile = userFileOptional.get();
userImg = userFile.getUrl();
}
return PostResponseDTO.PostSearchRes.builder()
.postId(post.getId())
.nickname(post.getUser().getNickname())
.userImg(userImg)
.title(post.getTitle())
.content(post.getContent())
.uploadDate(post.getCreatedAt())
.like(likeCount)
.comment(commentCount)
.isLike(isLike)
.isComment(isComment)
.build();
}

public static PostResponseDTO.PostSearchList PostSearchListDTO(Page<Post> postList, Long userId) {
List<PostResponseDTO.PostSearchRes> postSearchLists = postList.stream()
.map(post -> PostSearchResDTO(post, userId)).collect(Collectors.toList());
return PostResponseDTO.PostSearchList.builder()
.reviewPostList(postSearchLists)
.isEnd(postList.isLast())
.build();
}
}


34 changes: 34 additions & 0 deletions src/main/java/friend/spring/repository/PostRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,38 @@ public interface PostRepository extends JpaRepository<Post, Long> {

@Query(value = "SELECT p FROM Post p JOIN p.postScrapList s JOIN p.category c WHERE s.user.id = :userId and c.id = :categoryId")
Page<Post> findCategoryDetail(Long userId, Long categoryId, PageRequest pageRequest);

@Query(value = "SELECT p FROM Post p WHERE p.title LIKE CONCAT('%',:search,'%') OR p.content LIKE CONCAT('%',:search,'%')")
Page<Post> findByKeyWord(String search, Pageable pageable);

@Query("SELECT p FROM Post p " +
"LEFT JOIN General_poll gp ON p.generalPoll.id = gp.id " +
"LEFT JOIN Gauge_poll ggp ON p.gaugePoll.id = ggp.id " +
"LEFT JOIN Card_poll cp ON p.cardPoll.id = cp.id " +
"WHERE p.postType = :vote " +
"AND p.state = :posting " +
"AND p.createdAt >= :minusDays " +
// 투표 마감 안 된 글들만 필터링
"AND (" +
" (gp.VoteOnGoing = true) OR " +
" (ggp.VoteOnGoing = true) OR " +
" (cp.VoteOnGoing = true)" +
") " +
// 로그인한 사용자가 투표 안 한 글들만 필터링
"AND (" +
" gp.id NOT IN (SELECT gv.generalPoll.id FROM General_vote gv WHERE gv.user.id = :userId) OR " +
" ggp.id NOT IN (SELECT gv.gaugePoll.id FROM Gauge_vote gv WHERE gv.user.id = :userId) OR " +
" cp.id NOT IN (SELECT gv.cardPoll.id FROM Card_vote gv WHERE gv.user.id = :userId)" +
") " +
//각 투표 유형에 대한 투표 수를 합산해(어차피 하나에만 값이 있음) 투표 수가 적은 순으로 정렬
"ORDER BY (" +
" (SELECT COUNT(gv.id) FROM General_vote gv WHERE gv.generalPoll.id = gp.id) + " +
" (SELECT COUNT(gv.id) FROM Gauge_vote gv WHERE gv.gaugePoll.id = ggp.id) + " +
" (SELECT COUNT(gv.id) FROM Card_vote gv WHERE gv.cardPoll.id = cp.id)" +
") ASC")
Page<Post> findPostsOrderByVoteCount(@Param("vote") PostType vote,
@Param("posting") PostState posting,
@Param("minusDays") LocalDateTime minusDays,
@Param("userId") Long userId,
Pageable pageable);
}
2 changes: 2 additions & 0 deletions src/main/java/friend/spring/service/PostQueryService.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,6 @@ public interface PostQueryService {
Page<Post> getReviewList(Integer page, Integer size, Integer arrange);

Page<Post> getParentPostList(Integer page, Integer size, HttpServletRequest request);
Page<Post> getPostSearch(Integer page, Integer size, String search);

}
6 changes: 6 additions & 0 deletions src/main/java/friend/spring/service/PostQueryServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,10 @@ public Page<Post> getParentPostList(Integer page, Integer size, HttpServletReque

}

@Override
@Transactional
public Page<Post> getPostSearch(Integer page, Integer size, String search) {
Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
return postRepository.findByKeyWord(search, pageable);
}
}
2 changes: 1 addition & 1 deletion src/main/java/friend/spring/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,5 @@ public interface PostService {
void deleteScrapPost(Long postId, HttpServletRequest request);

PostResponseDTO.ReportResult createReportPost(Long postId, PostRequestDTO.PostReportReq request, HttpServletRequest request2);
}

}
20 changes: 13 additions & 7 deletions src/main/java/friend/spring/service/PostServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -414,15 +414,21 @@ public PostResponseDTO.PollPostGetListDTO getBestPosts(Integer page, Integer siz
@Override
public PostResponseDTO.PollPostGetListDTO getRecentPosts(Integer page, Integer size, HttpServletRequest request) {
Long userId = jwtTokenProvider.getCurrentUser(request);
Optional<User> optionalUser = userRepository.findById(userId);
if (optionalUser.isEmpty()) {
userService.checkUser(false);
}
User user = userRepository.findById(userId)
.orElseThrow(() -> new GeneralException(USER_NOT_FOUND));

LocalDateTime minusDays = LocalDateTime.now().minusDays(7); // 7일 이내(임시)
Pageable pageable = PageRequest.of(page, size);
Page<Post> recentPostPage = postRepository.findPostsOrderByVoteCount(PostType.VOTE, PostState.POSTING, minusDays, user.getId(), pageable);

Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
Page<Post> recentPostPage = postRepository.findByPostTypeAndState(PostType.VOTE, PostState.POSTING, pageable);
// 랜덤으로 섞기
List<Post> postList = new ArrayList<>(recentPostPage.getContent());
// 리스트를 랜덤하게 섞기
Collections.shuffle(postList);
// 섞인 리스트를 페이지로 다시 변환
Page<Post> shuffledPage = new PageImpl<>(postList, recentPostPage.getPageable(), postList.size());

return PostConverter.pollPostGetListDTO(recentPostPage, userId);
return PostConverter.pollPostGetListDTO(shuffledPage, userId);
}

@Override
Expand Down
19 changes: 19 additions & 0 deletions src/main/java/friend/spring/web/controller/PostRestController.java
Original file line number Diff line number Diff line change
Expand Up @@ -326,4 +326,23 @@ public ApiResponse<PostResponseDTO.PostReportRes> createReportPost(
PostResponseDTO.ReportResult postReport = postService.createReportPost(postId, request, request2);
return ApiResponse.onSuccess(PostConverter.toPostReportRes(postReport));
}

// 글 검색
@GetMapping("/post/search/")
@Operation(summary = "글 검색 API", description = "글을 검색합니다")
@Parameters({
@Parameter(name = "page", description = "query string(RequestParam) - 몇번째 페이지인지 가리키는 page 변수 입니다! (0부터 시작)"),
@Parameter(name = "size", description = "query string(RequestParam) - 몇 개씩 불러올지 개수를 세는 변수입니다. (1 이상 자연수로 설정)"),
@Parameter(name = "atk", description = "RequestHeader - 로그인한 사용자의 accessToken"),
@Parameter(name = "search", description = "query string(RequestParam) - 검색어.")
})
public ApiResponse<PostResponseDTO.PostSearchList> getPostSearch(@RequestParam(name = "page", defaultValue = "0") Integer page,
@RequestParam(name = "size", defaultValue = "15") Integer size,
@RequestParam(name = "search") String search,
@RequestHeader("atk") String atk,
HttpServletRequest request2) {
Long userId = jwtTokenService.JwtToId(request2);
Page<Post> postPage = postQueryService.getPostSearch(page, size, search);
return ApiResponse.onSuccess(PostConverter.PostSearchListDTO(postPage, userId));
}
}
26 changes: 26 additions & 0 deletions src/main/java/friend/spring/web/dto/PostResponseDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,32 @@ public static class ScrapCreateRes {
Long post_scrap_id;
}

@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class PostSearchList {
List<PostSearchRes> reviewPostList;
private Boolean isEnd;
}

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class PostSearchRes{
Long postId;
String nickname;
String userImg;
String title;
String content;
LocalDateTime uploadDate;
Integer like;
Integer comment;
Boolean isLike;
Boolean isComment;
}

@Builder
@Getter
@NoArgsConstructor
Expand Down

0 comments on commit c6c771c

Please sign in to comment.