항해99
23.10.06 항해 99 16기 실전 프로젝트 3일차
김용글
2023. 10. 6. 21:56
오늘 공부한 것
* 실전 프로젝트 댓글기능 구현
아직 프로젝트 초반이라 그런지 회의가 많았다
기능도 완벽히 픽스되지 않았고 자잘자잘한 것들이 의외로 걸리는 부분들이 많았기 때문이다
중간중간 나는 내가 맡은 댓글 기능을 구현했다
일단 쭉 구현중이기 때문에 내일은 많이 빼고 더하고를 해야할꺼 같다
또한, 기능들을 나누어서 구현중이라서 빨간줄이 너무 많이 떳다.. ㅠㅠ
테스트코드를 만들지 않는한 바로 확인은 어려울듯하니 잘못된 코드가 없는지 짚어볼 예정이다
코드 확인이 끝나면 내일은 대댓글 기능에 도전해보려고한다!
1. Controller
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class CommentController {
private final CommentsService commentsService;
// 댓글 생성
@PostMapping("/post/{postid}/comments")
public ResponseEntity<CommentsResponseDto> commentsCreate(@PathVariable("postid") Long postid,
@RequestBody CommentsRequestDto requestDto,
@AuthenticationPrincipal UserDetailsImpl userDetails) {
return ResponseEntity.ok(commentsService.commentsCreate(postid, requestDto, userDetails));
}
// 댓글 조회
@GetMapping("/post/{postid}/comments")
public ResponseEntity<List<CommentsResponseDto>> commentsList(@PathVariable("postid") Long postid) {
return ResponseEntity.ok(commentsService.commentsList(postid));
}
// 댓글 수정
@PutMapping("/post/{postid}/comments/{commentsid}")
public ResponseEntity<CommentsResponseDto> commentsUpdate(@PathVariable("postid") Long postid,
@PathVariable("commentsid") Long commentsid,
@RequestBody CommentsRequestDto request,
@AuthenticationPrincipal UserDetailsImpl userDetails) {
return ResponseEntity.ok(commentsService.commentsUpdate(postid, commentsid, request, userDetails));
}
// 댓글 삭제
@DeleteMapping("/post/{postid}/comments/{commentsid}")
public ResponseEntity<MessageResponseDto> commentsDelete(@PathVariable("postid") Long postid,
@PathVariable("commentsid") Long commentsid,
@AuthenticationPrincipal UserDetailsImpl userDetails) {
return ResponseEntity.ok(commentsService.commentsDelete(postid, commentsid, userDetails));
}
}
2. Entity
대댓글 기능을 추후 구현 예정이고 OneToMany 양방향으로 관계를 설정하였다
package com.sparta.team2project.comments.entity;
import com.sparta.team2project.comments.dto.CommentsRequestDto;
import com.sparta.team2project.commons.entity.Timestamped;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Entity
@Getter
@NoArgsConstructor
@Table(name = "comments")
public class Comments extends Timestamped {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String nickname;
@Column(nullable = false, length = 500)
private String contents;
//
// @ManyToOne
// @JoinColumn(name = "replies_id")
// private Replies replies;
public Comments(CommentsRequestDto requestDto) {
this.nickname = requestDto.getNickname();
this.contents = requestDto.getContents();
}
public void update(CommentsRequestDto requestDto) {
this.nickname = requestDto.getNickname();
this.contents = requestDto.getContents();
}
}
3. Dto
@Getter
public class CommentsRequestDto {
private String nickname;
private String contents;
}
@Getter
public class CommentsResponseDto {
private Long id;
private String contents;
private String nickname;
private LocalDateTime createAt;
private LocalDateTime modifiedAt;
public CommentsResponseDto(Comments comments) {
this.id = comments.getId();
this.contents = comments.getContents();
this.nickname = comments.getNickname();
this.createAt = comments.getCreatedAt();
this.modifiedAt = comments.getModifiedAt();
}
}
4. Repository
public interface CommentsRepository extends JpaRepository<Comments, Long> {
List<Comments> findByPostIdOrderByCreatedAtDesc(Long postid);
}
5. Service
@Service
@RequiredArgsConstructor
public class CommentsService {
private final CommentsRepository commentsRepository;
private final PostsRepository postsRepository;
// 댓글 생성
public CommentsResponseDto commentsCreate(Long postid,
CommentsRequestDto requestDto,
UserDetailsImpl userDetails) {
Posts posts = postsRepository.findById(postid).orElseThrow(
() -> new CustomException(ErrorCode.POST_NOT_EXIST));
Comments comments = new Comments(requestDto);
posts.addComments(comments);
MessageResponseDto messageResponseDto = new MessageResponseDto(
"댓글을 작성하였습니다", 200
);
return CommentsResponseDto(commentsRepository.save(comments, userDetails.getEmail()));
}
// 댓글 조회
public List<CommentsResponseDto> commentsList(Long postid) {
return commentsRepository.findByPostIdOrderByCreatedAtDesc(postid).stream().map(CommentsResponseDto::new).toList();
}
// 댓글 수정
@Transactional
public CommentsResponseDto commentsUpdate(Long postid,
Long commentsid,
CommentsRequestDto request,
UserDetailsImpl userDetails) {
Posts posts = postsRepository.findById(postid).orElseThrow(
() -> new CustomException(ErrorCode.POST_NOT_EXIST));
Comments comments = findById(commentsid);
if (users.getRoleEnum() == UsersRoleEnum.ADMIN) {
comments.update(request, userDetails.getEmail());
MessageResponseDto messageResponseDto = new MessageResponseDto(
"댓글을 수정하였습니다", 200
);
return new CommentsResponseDto(comments);
} else {
if (userDetails.equals(users.getEmail())) {
comments.update(request, userDetails.getEmail);
MessageResponseDto messageResponseDto = new MessageResponseDto(
"댓글을 수정하였습니다", 200
);
return new CommentsResponseDto(comments);
} else {
throw new CustomException(ErrorCode.NOT_ALLOWED);
}
}
}
// 댓글 삭제
public MessageResponseDto commentsDelete(Long postid, Long commentsid, UserDetailsImpl userDetails) {
Posts posts = postsRepository.findById(postid).orElseThrow(
() -> new CustomException(ErrorCode.POST_NOT_EXIST));
Comments comments = findById(commentsid);
if (users.getRoleEnum() == UsersRoleEnum.ADMIN) {
commentsRepository.delete(userDetails.getEmail());
return new MessageResponseDto("댓글을 삭제하였습니다", 200);
} else {
if (userDetails.equals(users.getEmail())) {
commentsRepository.delete(userDetails.getEmail());
MessageResponseDto messageResponseDto = new MessageResponseDto(
"댓글을 삭제하였습니다", 200
);
return new MessageResponseDto("댓글을 삭제하였습니다", 200);
} else {
throw new CustomException(ErrorCode.NOT_ALLOWED);
}
}
}
}