Comment 엔티티를 대신할 CommentDto 생성
package project.stylemate.dto;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class CommentDto {
private Long memberId;
private Long styleId;
private String content;
@Builder
public CommentDto(Long memberId, Long styleId, String content) {
this.memberId = memberId;
this.styleId = styleId;
this.content = content;
}
}
Comment 엔티티에 Dto로 변환하는 메서드 추가
public CommentDto toDto() {
return CommentDto.builder()
.memberId(this.member.getId())
.styleId(this.style.getId())
.content(this.content)
.build();
}
컨트롤러
@GetMapping("/api/v1/styles/{styleId}/comments")
public ApiResponse<List<CommentDto>> getAllCommentsByStyleId(@PathVariable Long styleId) {
List<Comment> comments = commentService.getAllCommentsByStyleId(styleId);
List<CommentDto> commentDtos = comments.stream()
.map(Comment::toDto)
.collect(Collectors.toList());
return ApiResponse.<List<CommentDto>>builder()
.code(SUCCESS_STATUS)
.message("댓글 조회 성공")
.data(commentDtos)
.build();
}
dto 생성
package project.stylemate.dto;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import project.stylemate.entity.Member;
import project.stylemate.entity.Style;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
@Getter
@NoArgsConstructor
public class SaveCommentRequest {
private Long memberId;
private String content;
}
서비스 코드 수정
public Comment saveComment(Long styleId, SaveCommentRequest saveCommentRequest) {
Style style = styleRepository.findById(styleId).orElseThrow(() -> new IllegalArgumentException());
Comment newComment = Comment.builder()
.style(style)
.member(memberRepository.findById(saveCommentRequest.getMemberId()).orElseThrow(() -> new IllegalArgumentException()))
.content(saveCommentRequest.getContent())
.build();
return commentRepository.save(newComment);
}
컨트롤러
@PostMapping("/api/v1/styles/{styleId}/comments")
public ApiResponse saveComment(@PathVariable Long styleId, @RequestBody SaveCommentRequest saveCommentRequest) {
commentService.saveComment(styleId, saveCommentRequest);
return ApiResponse.builder()
.code(SUCCESS_STATUS)
.message("댓글 등록 성공")
.build();
}