Skip to content

Commit

Permalink
fix : 커뮤니티 포스트 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
moonyaeyoon committed Sep 12, 2024
1 parent 2a746b3 commit 28b1271
Show file tree
Hide file tree
Showing 5 changed files with 12 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

public interface PostRepository extends JpaRepository<Post, Long> {

@Query("SELECT p FROM Post p WHERE p.postType = :postType AND (:cursor IS NULL OR p.id > :cursor) ORDER BY p.id ASC")
@Query("SELECT p FROM Post p WHERE p.postType = :postType AND p.isDraft = false AND (:cursor IS NULL OR p.id > :cursor) ORDER BY p.id ASC")
List<Post> findByPostTypeAndCursor(@Param("postType") PostType postType, @Param("cursor") Long cursor, Pageable pageable);

Slice<Post> findAllByAccountAndDeletedAtIsNullOrderByIdDesc(Account account, Pageable page);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ public ResponseEntity<ResponseData<PostsListResponse>> getPostList(@CurrentUser

@GetMapping("/{postId}")
@Operation(summary = "커뮤니티 글 내용 조회", description = "postId로 커뮤니티 글 내용을 조회합니다.")
public ResponseEntity<ResponseData<PostDetailResponse>> getPostDetail(@CurrentUser Account account, @PathVariable Long postId, @RequestParam(required = false, name = "cursor") Long cursor, @RequestParam(name = "pageSize") Integer pageSize) {
public ResponseEntity<ResponseData<PostDetailResponse>> getPostDetail(@CurrentUser Account account, @PathVariable Long postId) {
try{
return ResponseData.toResponseEntity(ResponseCode.POST_DETAIL_FETCH_SUCCEESS,postService.getPostDetail(postId,cursor, pageSize));
return ResponseData.toResponseEntity(ResponseCode.POST_DETAIL_FETCH_SUCCEESS,postService.getPostDetail(postId));
}catch (NoSuchElementException e) {
return ResponseData.toResponseEntity(ResponseCode.POST_NOT_FOUND, null);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package meltingpot.server.post.dto;

import lombok.*;
import meltingpot.server.comment.dto.CommentsListResponse;
import meltingpot.server.domain.entity.post.Post;
import java.time.LocalDateTime;
import java.util.List;
Expand All @@ -19,7 +18,6 @@ public class PostDetailResponse {
private String content;
private List<ImageData> imgData; // Image data including ID and URL
private Integer commentCount;
private CommentsListResponse commentsList;
private LocalDateTime updatedAt;

// Static nested class to hold image data
Expand All @@ -31,7 +29,7 @@ public static class ImageData {
private String imageUrl;
}

public static PostDetailResponse of(Post post, CommentsListResponse commentsList) {
public static PostDetailResponse of(Post post) {
List<ImageData> imgData = post.getPostImages().stream()
.map(postImage -> new ImageData(postImage.getId(), postImage.getImageUrl()))
.collect(Collectors.toList());
Expand All @@ -48,7 +46,6 @@ public static PostDetailResponse of(Post post, CommentsListResponse commentsList
.content(post.getContent())
.imgData(imgData)
.commentCount(commentCount)
.commentsList(commentsList)
.updatedAt(post.getUpdatedAt())
.build();
}
Expand Down
79 changes: 7 additions & 72 deletions src/main/java/meltingpot/server/post/service/PostService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,12 @@


import lombok.*;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Collectors;

import meltingpot.server.comment.dto.CommentsListResponse;
import meltingpot.server.domain.entity.Account;
import meltingpot.server.domain.entity.comment.Comment;
import meltingpot.server.domain.entity.post.Post;
import meltingpot.server.domain.entity.enums.PostType;
import meltingpot.server.domain.entity.post.PostImage;
Expand Down Expand Up @@ -52,13 +48,7 @@ public ResponseCode createPost(PostCreateRequest postCreateRequest, Account acco
updatePostContent(post, account, postCreateRequest);
}
setPostImages(post, account, postCreateRequest);
// isDraft 값을 설정하기 전에 현재 상태 출력
System.out.println("Setting isDraft for post with ID " + post.getId() + " to " + isDraft);
post.setIsDraft(isDraft);

// isDraft 값 설정 후 출력
System.out.println("Post isDraft status: " + post.getIsDraft());

postRepository.save(post);

return isDraft ? ResponseCode.DRAFT_SAVE_SUCCESS : ResponseCode.CREATE_POST_SUCCESS;
Expand All @@ -79,10 +69,12 @@ public ResponseCode updatePost(PostCreateRequest updateRequest,Long postId, Acco

/*post 내용 불러오기*/
@Transactional(readOnly = true)
public PostDetailResponse getPostDetail(Long postId, Long cursor, int pageSize){
public PostDetailResponse getPostDetail(Long postId){
Post post = findPostById(postId);
CommentsListResponse commentsList = fetchCommentsList(postId, cursor, pageSize);
return PostDetailResponse.of(post,commentsList);
if(post.getIsDraft()){
throw new IllegalStateException("게시물 조회 실패");
}
return PostDetailResponse.of(post);
}

/*post 목록 불러오기*/
Expand Down Expand Up @@ -171,65 +163,6 @@ private List<PostImage> createPostImages(List<String> imageKeys, Post post, Acco
.collect(Collectors.toList());
}

private CommentsListResponse fetchCommentsList(Long postId, Long cursor, int pageSize) {
List<CommentsListResponse.CommentDetail> commentDetailDTOs = new ArrayList<>();
int count = 0;
Long parentCursor = null;

// Cursor가 자식 댓글에 해당하는 경우 처리
if (cursor != null) {
Comment cursorComment = commentRepository.findById(cursor).orElse(null);
if (cursorComment != null) {
Comment parentComment;
if (cursorComment.getParent() != null) {
// Cursor가 자식 댓글을 나타내는 경우
parentComment = cursorComment.getParent();
} else {
// Cursor가 부모 댓글을 나타내는 경우
parentComment = cursorComment;
}

List<Comment> remainingChildren = commentRepository.findChildrenCommentsByParentId(parentComment.getId(), cursor);
for (Comment child : remainingChildren) {
if (count >= pageSize) break;
commentDetailDTOs.add(CommentsListResponse.CommentDetail.from(child));
count++;
}
parentCursor = parentComment.getId();

// 만약 자식 댓글을 모두 가져왔고, 페이지가 꽉 차지 않았다면 다음 부모 댓글로 넘어감
if (count < pageSize && remainingChildren.size() < pageSize) {
parentCursor = parentComment.getId();
}
} else {
parentCursor = cursor; // cursor가 부모 댓글인 경우
}
}

// 부모 댓글과 자식 댓글을 가져오는 처리
if (count < pageSize) {
Pageable pageable = PageRequest.of(0, pageSize - count);
List<Comment> parentComments = commentRepository.findParentCommentsByPostId(postId, parentCursor, pageable);
for (Comment parent : parentComments) {
if (count >= pageSize) break;
commentDetailDTOs.add(CommentsListResponse.CommentDetail.from(parent));
count++;

List<Comment> children = commentRepository.findChildrenCommentsByParentId(parent.getId(), null);
for (Comment child : children) {
if (count >= pageSize) break;
commentDetailDTOs.add(CommentsListResponse.CommentDetail.from(child));
count++;
}
}
}

Long nextCursor = (count < pageSize) ? null : commentDetailDTOs.get(commentDetailDTOs.size() - 1).getCommentId();
boolean isLast = (count < pageSize);

return CommentsListResponse.from(commentDetailDTOs, nextCursor, isLast);
}

private Optional<Post> getDraftPost(Account account) {
return postRepository.findByAccountAndIsDraftTrue(account);
}
Expand All @@ -238,5 +171,7 @@ private void setPostImages(Post post, Account account,PostCreateRequest postRequ
List<PostImage> postImages = createPostImages(postRequest.getImageKeys(), post, account);
post.setPostImages(postImages);
}


}

1 change: 1 addition & 0 deletions src/main/java/meltingpot/server/util/ResponseCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ public enum ResponseCode {
POST_CREATE_FAIL(BAD_REQUEST, "게시글 작성 실패"),
POST_UPDATE_FAIL(BAD_REQUEST,"게시글 수정 실패"),
POST_DELETE_FAIL(BAD_REQUEST,"게시글 삭제 실패"),
POST_FETCH_FAIL(BAD_REQUEST,"게시글 조회 실패"),
REPORT_CREATE_FAIL(BAD_REQUEST, "신고 작성 실패"),
AREA_FETCH_FAILED(BAD_REQUEST, "지역 조회 실패"),
AREA_FETCH_FAILED_NOT_SERVICE_AREA(BAD_REQUEST, "현재 좌표 조회는 국내에서만 사용 가능합니다"),
Expand Down

0 comments on commit 28b1271

Please sign in to comment.