Skip to content

Commit

Permalink
Refactor/bookmark postservice : 북마크 서비스에 댓글 추가 및 댓글 서비스 수정 (#164)
Browse files Browse the repository at this point in the history
* refactor/bookmark-postservice-1: 북마크에 댓글 추가
- 다대일로 댓글-북마크 관계
- 북마크 생성할 때 DTO에 type 추가해 활용
- 게시글 반응 DTO에 댓글 추가
- 댓글 생성 엔드포인트 수정

* refactor/bookmark-postservice-2: 북마크 두번 생성할 수 없도록
- JPA를 이용해 중복된 북마크를 만들 수 없도록 함

* refactor/bookmark-postservice-3: 댓글 서비스 수정
- CommentService:
- 댓글/대댓글은 게시글 번호에 따른 댓글 조회 시 포함되게 됨
- 대댓글 또한 DTO 조회 시에 좋아요와 스크랩수를 포함해야 하기 때문에 기존에 DTO에 포함했던 대댓글 정보를 댓글 DTO처럼 밖으로 빼고 parent_id로 구별함 -> parent_id가 null이라면 최초 댓글인것이고 null이 아니라면 대댓글인 것임

* refactor/bookmark-postservice-4: 북마크 취소
- 북마크 취소 버튼을 누를 시 북마크가 삭제됨 (좋아요 서비스와 동일)

* refactor/bookmark-postservice-5: consume 타입 application/json 삭제

* refactor/bookmark-postservice-6: 게시글&댓글 불러오기 피드백 반영
- CommentResponseDto, CommentService:
- 댓글 응답 DTO에 부모 댓글 ID가 아닌 부모 댓글 엔티티를 가져옴
 - PostResponseDto:
 - 게시글 조회 시 댓글 리스트는 보이지 않음 -> 댓글은 댓글 조회 엔드포인트를 통해 이루어짐

* refactor/bookmark-postservice-7: 누락된 List import 추가
  • Loading branch information
KooSuYeon authored Jul 11, 2024
1 parent 7559057 commit 643eb95
Show file tree
Hide file tree
Showing 17 changed files with 156 additions and 24 deletions.
10 changes: 9 additions & 1 deletion src/main/java/com/dife/api/controller/BookmarkController.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.dife.api.controller;

import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;

import com.dife.api.model.dto.BookmarkCreateRequestDto;
import com.dife.api.model.dto.BookmarkResponseDto;
Expand All @@ -27,7 +28,7 @@ public ResponseEntity<List<BookmarkResponseDto>> getAllBookmarks(Authentication
return ResponseEntity.ok(bookmarks);
}

@PostMapping(consumes = "application/json")
@PostMapping
public ResponseEntity<BookmarkResponseDto> createBookmark(
@RequestBody BookmarkCreateRequestDto requestDto, Authentication auth) {
BookmarkResponseDto responseDto = bookmarkService.createBookmark(requestDto, auth.getName());
Expand All @@ -41,4 +42,11 @@ public ResponseEntity<List<BookmarkResponseDto>> getBookmarkChats(
bookmarkService.getBookmarks(chatroomId, authentication.getName());
return ResponseEntity.ok(bookmarks);
}

@DeleteMapping
public ResponseEntity<Void> deleteBookmarkPost(
@RequestBody BookmarkCreateRequestDto requestDto, Authentication auth) {
bookmarkService.deleteBookmark(requestDto, auth.getName());
return new ResponseEntity<>(OK);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public ResponseEntity<ChatroomResponseDto> createChatroom(
return ResponseEntity.status(CREATED).body(responseDto);
}

@PutMapping(value = "/{id}", consumes = "application/json")
@PutMapping("/{id}")
public ResponseEntity<ChatroomResponseDto> update(
@RequestBody GroupChatroomPutRequestDto requestDto,
@PathVariable(name = "id") Long chatroomId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
public class CommentController implements SwaggerCommentController {
private final CommentService commentService;

@PostMapping(value = "/{postId}", consumes = "application/json")
@PostMapping
public ResponseEntity<CommentResponseDto> createComment(
@RequestBody CommentCreateRequestDto requestDto, Authentication auth) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public ResponseEntity<ConnectResponseDto> getConnect(
return ResponseEntity.status(OK).body(responseDto);
}

@PostMapping(value = "/", consumes = "application/json")
@PostMapping("/")
public ResponseEntity<ConnectResponseDto> createConnect(
@Valid @RequestBody ConnectRequestDto requestDto, Authentication auth) {
ConnectResponseDto responseDto = connectService.saveConnect(requestDto, auth.getName());
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/dife/api/controller/LikeController.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public ResponseEntity<List<PostResponseDto>> getLikedPosts(Authentication auth)
return ResponseEntity.status(OK).body(responseDto);
}

@PostMapping(consumes = "application/json")
@PostMapping
public ResponseEntity<Void> createLike(
@RequestBody LikeCreateRequestDto requestDto, Authentication auth) {

Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/dife/api/controller/MemberController.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class MemberController implements SwaggerMemberController {
private final MemberService memberService;
private final JWTUtil jwtUtil;

@PostMapping(value = "/register", consumes = "application/json")
@PostMapping("/register")
public ResponseEntity<RegisterResponseDto> registerEmailAndPassword(
@Valid @RequestBody RegisterEmailAndPasswordRequestDto dto) {
RegisterResponseDto responseDto = memberService.registerEmailAndPassword(dto);
Expand Down Expand Up @@ -87,12 +87,12 @@ public ResponseEntity<MemberResponseDto> profile(Authentication auth) {
return ResponseEntity.ok(responseDto);
}

@PostMapping(value = "/login", consumes = "application/json")
@PostMapping("/login")
public ResponseEntity<LoginSuccessDto> login(@Valid @RequestBody LoginDto dto) {
return memberService.login(dto);
}

@PostMapping(value = "/refresh-token", consumes = "application/json")
@PostMapping("/refresh-token")
public ResponseEntity<Void> checkToken(@Valid @RequestBody RefreshTokenRequestDto requestDto) {

boolean isTokenExpired = jwtUtil.isExpired(requestDto.getToken());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,8 @@ ResponseEntity<BookmarkResponseDto> createBookmark(
})
ResponseEntity<List<BookmarkResponseDto>> getBookmarkChats(
@PathVariable(name = "chatroomId") Long chatroomId, Authentication authentication);

@Operation(summary = "북마크 취소 API", description = "사용자가 DTO를 작성해 게시글/댓글 북마크를 취소하는 API입니다.")
@ApiResponse(responseCode = "200")
ResponseEntity<Void> deleteBookmarkPost(BookmarkCreateRequestDto requestDto, Authentication auth);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.dife.api.exception;

public class DuplicateBookmarkException extends DuplicateException {

public DuplicateBookmarkException() {
super("이미 북마크를 눌렀습니다!");
}
}
4 changes: 4 additions & 0 deletions src/main/java/com/dife/api/model/Bookmark.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,8 @@ public class Bookmark {
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;

@ManyToOne
@JoinColumn(name = "comment_id")
private Comment comment;
}
7 changes: 7 additions & 0 deletions src/main/java/com/dife/api/model/BookmarkType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.dife.api.model;

public enum BookmarkType {
CHAT,
POST,
COMMENT
}
5 changes: 5 additions & 0 deletions src/main/java/com/dife/api/model/Comment.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,10 @@ public class Comment extends BaseTimeEntity {
private List<Comment> childrenComments = new ArrayList<>();

@OneToMany(mappedBy = "comment", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JsonIgnore
private List<LikeComment> CommentLikes;

@OneToMany(mappedBy = "comment", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JsonIgnore
private List<Bookmark> Bookmarks;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.dife.api.model.dto;

import com.dife.api.model.BookmarkType;
import lombok.*;

@Getter
Expand All @@ -9,7 +10,9 @@
@NoArgsConstructor
public class BookmarkCreateRequestDto {

private BookmarkType type;
private Long chatroomId;
private Long chatId;
private Long postId;
private Long commentId;
}
2 changes: 2 additions & 0 deletions src/main/java/com/dife/api/model/dto/BookmarkResponseDto.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.dife.api.model.dto;

import com.dife.api.model.Comment;
import com.dife.api.model.Post;
import lombok.*;

Expand All @@ -13,4 +14,5 @@ public class BookmarkResponseDto {
private Long id;
private String message;
private Post post;
private Comment comment;
}
7 changes: 4 additions & 3 deletions src/main/java/com/dife/api/model/dto/CommentResponseDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import java.util.List;
import lombok.*;

@Getter
Expand All @@ -21,13 +20,15 @@ public class CommentResponseDto {

private Boolean isPublic;

private Comment parentComment;

private Integer likesCount;

private Integer bookmarkCount;

@JsonProperty("writer")
private Member writer;

private List<Comment> childrenComments;

@Schema(description = "프로필 생성 일시")
private LocalDateTime created;

Expand Down
13 changes: 13 additions & 0 deletions src/main/java/com/dife/api/repository/BookmarkRepository.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package com.dife.api.repository;

import com.dife.api.model.Bookmark;
import com.dife.api.model.Comment;
import com.dife.api.model.Member;
import com.dife.api.model.Post;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
Expand All @@ -17,4 +20,14 @@ List<Bookmark> findBookmarksByMemberAndChatroomId(
@Param("chatroomId") Long chatroomId, @Param("member") Member member);

List<Bookmark> findAllByMember(Member member);

boolean existsBookmarkByPostAndMember(Post post, Member member);

Optional<Bookmark> findBookmarkByPostAndMember(Post post, Member member);

boolean existsBookmarkByCommentAndMember(Comment comment, Member member);

Optional<Bookmark> findBookmarkByCommentAndMember(Comment comment, Member member);

boolean existsBookmarkByMessage(@Param("message") String message);
}
75 changes: 73 additions & 2 deletions src/main/java/com/dife/api/service/BookmarkService.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public class BookmarkService {
private final ChatroomRepository chatroomRepository;
private final ChatRepository chatRepository;
private final PostRepository postRepository;
private final CommentRepository commentRepository;
private final MemberRepository memberRepository;
private final ModelMapper modelMapper;

Expand Down Expand Up @@ -59,8 +60,15 @@ public List<BookmarkResponseDto> getBookmarks(Long chatroomId, String memberEmai

public BookmarkResponseDto createBookmark(
BookmarkCreateRequestDto requestDto, String memberEmail) {
if (requestDto.getPostId() != null) return createBookmarkPost(requestDto, memberEmail);
return createBookmarkChat(requestDto, memberEmail);

switch (requestDto.getType()) {
case POST:
return createBookmarkPost(requestDto, memberEmail);
case COMMENT:
return createBookmarkComment(requestDto, memberEmail);
default:
return createBookmarkChat(requestDto, memberEmail);
}
}

public BookmarkResponseDto createBookmarkChat(
Expand All @@ -73,6 +81,8 @@ public BookmarkResponseDto createBookmarkChat(
.findByChatroomIdAndId(requestDto.getChatroomId(), requestDto.getChatId())
.orElseThrow(() -> new ChatroomException("유효하지 않은 채팅입니다!"));

if (bookmarkRepository.existsBookmarkByMessage(chat.getMessage()))
throw new DuplicateBookmarkException();
Bookmark bookmark = new Bookmark();
bookmark.setMessage(chat.getMessage());
bookmark.setMember(member);
Expand All @@ -90,11 +100,72 @@ public BookmarkResponseDto createBookmarkPost(
postRepository.findById(requestDto.getPostId()).orElseThrow(PostNotFoundException::new);
if (!post.getIsPublic()) throw new PostUnauthorizedException();

if (bookmarkRepository.existsBookmarkByPostAndMember(post, member))
throw new DuplicateBookmarkException();

Bookmark bookmark = new Bookmark();
bookmark.setPost(post);
bookmark.setMember(member);
bookmarkRepository.save(bookmark);

return modelMapper.map(bookmark, BookmarkResponseDto.class);
}

public BookmarkResponseDto createBookmarkComment(
BookmarkCreateRequestDto requestDto, String memberEmail) {

Member member =
memberRepository.findByEmail(memberEmail).orElseThrow(MemberNotFoundException::new);

Comment comment =
commentRepository
.findById(requestDto.getCommentId())
.orElseThrow(() -> new CommentNotFoundException());

if (bookmarkRepository.existsBookmarkByCommentAndMember(comment, member))
throw new DuplicateBookmarkException();

Bookmark bookmark = new Bookmark();
bookmark.setMember(member);
bookmark.setComment(comment);
bookmarkRepository.save(bookmark);

return modelMapper.map(bookmark, BookmarkResponseDto.class);
}

public void deleteBookmark(BookmarkCreateRequestDto requestDto, String memberEmail) {
Member member =
memberRepository.findByEmail(memberEmail).orElseThrow(MemberNotFoundException::new);

switch (requestDto.getType()) {
case POST:
Post post =
postRepository.findById(requestDto.getPostId()).orElseThrow(PostNotFoundException::new);

Bookmark bookmarkPost =
bookmarkRepository
.findBookmarkByPostAndMember(post, member)
.orElseThrow(PostNotFoundException::new);

bookmarkPost.getPost().getBookmarks().remove(bookmarkPost);
member.getBookmarks().remove(bookmarkPost);
bookmarkRepository.delete(bookmarkPost);
break;

case COMMENT:
Comment comment =
commentRepository
.findById(requestDto.getCommentId())
.orElseThrow(CommentNotFoundException::new);

Bookmark bookmarkComment =
bookmarkRepository
.findBookmarkByCommentAndMember(comment, member)
.orElseThrow(LikeNotFoundException::new);

bookmarkComment.getComment().getBookmarks().remove(bookmarkComment);
bookmarkRepository.delete(bookmarkComment);
break;
}
}
}
28 changes: 17 additions & 11 deletions src/main/java/com/dife/api/service/CommentService.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,10 @@ public class CommentService {

@Transactional(readOnly = true)
public List<CommentResponseDto> getCommentsByPostId(Long postId) {

Post post = postRepository.findById(postId).orElseThrow(PostNotFoundException::new);
List<Comment> comments = commentRepository.findCommentsByPost(post);

return comments.stream()
.map(
comment -> {
CommentResponseDto dto = modelMapper.map(comment, CommentResponseDto.class);
dto.setLikesCount(comment.getCommentLikes().size());
return dto;
})
.collect(Collectors.toList());
return comments.stream().map(this::getComment).collect(Collectors.toList());
}

public CommentResponseDto createComment(CommentCreateRequestDto requestDto, String memberEmail) {
Expand All @@ -56,7 +48,7 @@ public CommentResponseDto createComment(CommentCreateRequestDto requestDto, Stri
? commentRepository.findById(requestDto.getParentCommentId()).orElse(null)
: null;
Comment comment = new Comment();
comment.setPost(parentComment == null ? post : null);
comment.setPost(post);
comment.setParentComment(parentComment);
comment.setWriter(writer);
comment.setContent(requestDto.getContent());
Expand All @@ -67,6 +59,20 @@ public CommentResponseDto createComment(CommentCreateRequestDto requestDto, Stri

commentRepository.save(comment);

return modelMapper.map(comment, CommentResponseDto.class);
CommentResponseDto responseDto = modelMapper.map(comment, CommentResponseDto.class);
if (comment.getParentComment() != null)
responseDto.setParentComment(comment.getParentComment());
return responseDto;
}

public CommentResponseDto getComment(Comment comment) {
CommentResponseDto dto = modelMapper.map(comment, CommentResponseDto.class);

dto.setLikesCount(comment.getCommentLikes().size());
dto.setBookmarkCount(comment.getBookmarks().size());

if (comment.getParentComment() != null) dto.setParentComment(comment.getParentComment());

return dto;
}
}

0 comments on commit 643eb95

Please sign in to comment.