엔티티를 dto로 변환

강우엉·2023년 10월 10일
0

study

목록 보기
22/44

응답 변환

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();

    }
profile
우엉이의 코딩 성장일기💻

0개의 댓글