inblog logo
|
sxias
    REST API

    [REST API] 17. Blog V3 : Reply

    문정준's avatar
    문정준
    May 15, 2025
    [REST API] 17. Blog V3 : Reply
    Contents
    REST API 서버는 데이터만 돌려주는 서버1. DTO Setting2. 댓글 작성3. 댓글 삭제
    ❗

    REST API 서버는 데이터만 돌려주는 서버

    • 변경된 값을 항상 다시 돌려줘야 함
    • GET, POST, PUT, DELETE
     

    1. DTO Setting

    • ReplyRequest
    @Data public static class SaveDTO { @NotNull(message = "board의 id가 전달되어야 합니다") private Integer boardId; @NotEmpty(message = "내용을 입력하세요") private String content; public Reply toEntity(User sessionUser) { return Reply.builder() .content(content) .board(Board.builder().id(boardId).build()) .user(sessionUser) .build(); } }
     
    • ReplyResponse
    @Data public static class DTO { private Integer id; private String content; private Integer userId; private Integer boardId; private String createdAt; // 날짜는 String으로 리턴한다 (날짜 타입 공부하기 전까지) public DTO(Reply reply) { this.id = reply.getId(); this.content = reply.getContent(); this.userId = reply.getUser().getId(); this.boardId = reply.getBoard().getId(); this.createdAt = reply.getCreatedAt().toString(); } }
     

    2. 댓글 작성

    • ReplyController
    @PostMapping("/s/api/reply") public ResponseEntity<?> save(@Valid @RequestBody ReplyRequest.SaveDTO reqDTO, Errors errors) { User sessionUser = (User) session.getAttribute("sessionUser"); ReplyResponse.DTO respDTO = replyService.댓글쓰기(reqDTO, sessionUser); return Resp.ok(respDTO); }
     
    • ReplyService
    @Transactional public ReplyResponse.DTO 댓글쓰기(ReplyRequest.SaveDTO reqDTO, User sessionUser) { Reply replyPS = replyRepository.save(reqDTO.toEntity(sessionUser)); return new ReplyResponse.DTO(replyPS); }
     

    Result

    3. 댓글 삭제

    • ReplyController
    @DeleteMapping("/s/api/reply/{id}") public ResponseEntity<?> delete(@PathVariable("id") Integer id) { User sessionUser = (User) session.getAttribute("sessionUser"); replyService.댓글삭제(id, sessionUser.getId()); return Resp.ok(null); }
     
    • ReplyService
    @Transactional public void 댓글삭제(Integer id, Integer sessionUserId) { Reply replyPS = replyRepository.findById(id) .orElseThrow(() -> new ExceptionApi404("자원을 찾을 수 없습니다")); if (!replyPS.getUser().getId().equals(sessionUserId)) { throw new ExceptionApi403("권한이 없습니다"); } replyRepository.deleteById(id); }
     

    Result

    Share article
    Contents
    REST API 서버는 데이터만 돌려주는 서버1. DTO Setting2. 댓글 작성3. 댓글 삭제

    Sxias ㆍ a32176740@gmail.com

    RSS·Powered by Inblog