Spring Level 3 댓글 작성 API 구현

song yuheon·2023년 9월 2일
0

Spring

목록 보기
36/93
post-thumbnail

Controller 구현


@PostMapping("/comment")
public CommentResponseDto createComment(@RequestBody CommentRequestDto requestDto, HttpServletRequest req) {
    User user = (User) req.getAttribute("user");

    return commentService.createComment(requestDto, user.getUsername());
}

Dto 구현


CommentResponseDto


반환 형식에 맞는 Dto 클래스 구현

package com.sparta.springlevel3.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.sparta.springlevel3.entity.Comment;
import lombok.Getter;

import java.time.LocalDateTime;
import java.util.List;

@Getter
public class CommentResponseDto { // 응답하는 Dto
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Long id;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Long postid;
    private String contents;
    private String username;
    private LocalDateTime createdAt;
    private LocalDateTime modifiedAt;

    public CommentResponseDto(Comment comment) {
        this.id = comment.getId();
        this.postid = comment.getPostid();
        this.contents = comment.getContents();
        this.username = comment.getUsername();
        this.createdAt = comment.getCreatedAt();
        this.modifiedAt = comment.getModifiedAt();
    }

    public CommentResponseDto() {}

    public CommentResponseDto(Long id, String contents, String username, LocalDateTime createdAt, LocalDateTime modifiedAt) {
        this.id = id;
        this.contents = contents;
        this.username = username;
        this.createdAt = createdAt;
        this.modifiedAt = modifiedAt;
    }

    public CommentResponseDto fromComment(Comment comment) {
        return new CommentResponseDto(comment.getId(), comment.getContents(), comment.getUsername(), comment.getCreatedAt(), comment.getModifiedAt());
    }
}

CommentRequestDto


클라이언트 요청 body 형식에 맞게 commentRequestDto 제작

package com.sparta.springlevel3.dto;
import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class CommentRequestDto {
    private Long postid;
    private String contents;
}

Service 구현


    public CommentResponseDto createComment(CommentRequestDto requestDto, String username) {
        // RequestDto -> Entity
        Comment comment = new Comment(requestDto, username);
        // DB 저장
        Comment saveComment = commentRepository.save(comment);
        // Entity -> ResponseDto
        CommentResponseDto commentResponseDto = new CommentResponseDto(saveComment);
        return commentResponseDto;
    }

Test



profile
backend_Devloper

0개의 댓글