TIL - 2024/05/30

2024. 5. 30. 16:19· TIL
목차
  1. 2️⃣단계 댓글 등록
  2. 기능
  3. 조건
  4. ⚠️ 예외 처리
  5. 전체적인 흐름
  6. 3️⃣단계 댓글 수정
  7. 기능
  8. 조건
  9. ⚠️ 예외 처리
  10. 4️⃣단계 댓글 삭제
  11. 기능
  12. 조건
  13. ⚠️ 예외 처리

개인 과제를 진행하고 있다

어렵지만 강의에서 구현한 코드 보고 공부하면서 보고 있다

 

2️⃣단계 댓글 등록

기능

● 선택한 일정이 있다면 댓글을 등록합니다.

조건

● 댓글이 등록되었다면 client에게 반환합니다.

● 선택한 일정이 DB에 저장되어 있어야 합니다.

● 댓글을 식별하는 고유번호, 댓글 내용, 댓글을 작성한 사용자 아이디,

댓글이 작성된 일정 아이디, 작성일자를 저장할 수 있습니다.

⚠️ 예외 처리

● 선택한 일정의 ID를 입력 받지 않은 경우

● 댓글 내용이 비어 있는 경우

● 일정이 DB에 저장되지 않은 경우

 

 

코드

@RestController
@RequestMapping("/api/comments")
@AllArgsConstructor
public class CommentController {
    private final CommentService commentService;

    @PostMapping
    public ResponseEntity<CommonResponse<CommentResponseDto>> createComment(@RequestBody CommentRequestDto commentRequestDto) {
        try {
            CommentResponseDto comment = commentService.createComment(commentRequestDto);
            return ResponseEntity.ok(
                    CommonResponse.<CommentResponseDto>builder()
                            .statusCode(HttpStatus.OK.value())
                            .msg("댓글이 성공적으로 추가되었습니다.")
                            .data(comment)
                            .build()
            );
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(
                    CommonResponse.<CommentResponseDto>builder()
                            .statusCode(HttpStatus.BAD_REQUEST.value())
                            .msg(e.getMessage())
                            .build()
            );
        }
    }

    @GetMapping("/schedule/{scheduleId}")
    public ResponseEntity<CommonResponse<List<CommentResponseDto>>> getCommentsByScheduleId(@PathVariable Long scheduleId) {
        List<CommentResponseDto> comments = commentService.getCommentsByScheduleId(scheduleId);
        return ResponseEntity.ok(
                CommonResponse.<List<CommentResponseDto>>builder()
                        .statusCode(HttpStatus.OK.value())
                        .msg("댓글 목록 조회가 완료되었습니다.")
                        .data(comments)
                        .build()
        );
    }
}

//댓글 관련 HTTP 요청을 처리하는 컨트롤러 

createComment 메서드 : post 요청 > commentService를 통해 댓글 생성함 

getCommentsByScheduleId 메서드 : 특정 일정 모든 댓글 조회

get요청을 받아서 commentService를 통해 반환

 

@Getter
public class CommentRequestDto {
    private String content;
    private String userId;
    private Long scheduleId;

    public void validate() {
        if (content == null || content.trim().isEmpty()) {
            throw new IllegalArgumentException("댓글 내용이 빕니다.");
        }
        if (scheduleId == null) {
            throw new IllegalArgumentException("일정 ID가 입력이 안됐습니다.");
        }
    }
}

//CommentRequestDto

댓글 요청 데이터를 담는 dto

validate 메서드 : 예외처리

@Service
@RequiredArgsConstructor
public class CommentService {

    private final CommentRepository commentRepository;
    private final ScheduleRepository scheduleRepository;

    public CommentResponseDto createComment(CommentRequestDto commentRequestDto) {
        commentRequestDto.validate();

        Schedule schedule = scheduleRepository.findById(commentRequestDto.getScheduleId())
                .orElseThrow(() -> new IllegalArgumentException("일정이 존재하지 않습니다"));
        Comment comment = new Comment(commentRequestDto.getContent(), commentRequestDto.getUserId(), schedule);
        Comment savedComment = commentRepository.save(comment);
        return new CommentResponseDto(savedComment);
    }

    public List<CommentResponseDto> getCommentsByScheduleId(Long scheduleId) {
        List<Comment> comments = commentRepository.findByScheduleId(scheduleId);
        return comments.stream()
                .map(CommentResponseDto::new)
                .collect(Collectors.toList());
    }
}

//CommentService

댓글 생성 + 조회 ,  비즈니스 로직 처리

Comment 레포랑 Schedule 레포 주입 받음

createComment 메서드: commentRequestDto 객체를 받아 댓글 생성 하고 dto 검증하고

일정이 존재 하는지 확인후 댓글 생성하여 저장 > 저장된 댓글을 dto로 변환하여 반환

 

전체적인 흐름

 

※클라이언트가 댓글을 생성 요청

1. POST /api/comments 엔드포인트에 CommentRequestDto를 포함하여 요청을 보냄

2. CommentController는 요청을 받아 CommentService의 createComment 메소드를 호출

3. CommentService는 요청 DTO를 검증하고, 일정이 존재하는지 확인한 후 댓글을 생성하여 저장

4. 생 성된 댓글을 DTO로 변환하여 CommonResponse 형태로 반환

 

※ 클라이언트가 특정 일정에 대한 댓글 조회 요청

1. GET /api/comments/schedule/{scheduleId} 엔드포인트에 요청을 보냄

2. CommentController는 요청을 받아 CommentService의 getCommentsByScheduleId 메소드를 호출

3. CommentService는 특정 일정 ID에 해당하는 모든 댓글을 조회하여

DTO로 변환한 후 CommonResponse 형태로 반환

 

3️⃣단계 댓글 수정

기능

● 선택한 일정의 댓글을 수정합니다

조건

● 댓글이 수정되었다면 수정된 댓글을 반환합니다 .

● 댓글 내용만 수정 가능합니다.

● 선택한 일정과 댓글이 DB에 저장되어 있어야 합니다.

⚠️ 예외 처리

● 선택한 일정이나 댓글의 ID를 입력 받지 않은 경우

● 일정이나 댓글이 DB에 저장되지 않은 경우

● 선택한 댓글의 사용자가 현재 사용자와 일치하지 않은 경우

    @PutMapping("/{id}")
    public ResponseEntity<CommonResponse<CommentResponseDto>> updateComment(@PathVariable Long id, @RequestBody UpdateCommentRequestDto updateCommentRequestDto) {
        try {
            CommentResponseDto updatedComment = commentService.updateComment(id, updateCommentRequestDto);
            return ResponseEntity.ok(
                    CommonResponse.<CommentResponseDto>builder()
                            .statusCode(HttpStatus.OK.value())
                            .msg("댓글이 성공적으로 수정되었습니다.")
                            .data(updatedComment)
                            .build()
            );
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(
                    CommonResponse.<CommentResponseDto>builder()
                            .statusCode(HttpStatus.BAD_REQUEST.value())
                            .msg(e.getMessage())
                            .build()
            );
        }
    }

//CommentController

댓글을 수정하려는 요청을 받아서 CommentService를 통해 댓글을 수정

 

@Getter
public class UpdateCommentRequestDto {
    private String content;
    private String userId;

    public void validate() {
        if (content == null || content.trim().isEmpty()) {
            throw new IllegalArgumentException("댓글 내용이 비어 있습니다.");
        }
    }
}

//UpdateCommentRequestDto

댓글 수정 요청 담는 데이터 전송 객체

    public CommentResponseDto updateComment(Long id, UpdateCommentRequestDto updateCommentRequestDto) {
        updateCommentRequestDto.validate();

        Comment comment = commentRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("댓글이 없습니다"));

        if (!comment.getUserId().equals(updateCommentRequestDto.getUserId())) {
            throw new IllegalArgumentException("댓글 작성자와 현재 사용자 불일치");
        }

        comment.setContent(updateCommentRequestDto.getContent());
        Comment updatedComment = commentRepository.save(comment);
        return new CommentResponseDto(updatedComment);
    }

//CommentService

댓글 수정 요청 처리

댓글 찾고 작성자와 수정 요청 작성자의 id가 일치하는지 확인

만약 일치한다 ? > 업데이트 , 수정 댓글 반환

 

4️⃣단계 댓글 삭제

기능

● 선택한 일정의 댓글을 삭제합니다.

조건

● 성공했다는 메시지와 상태 코드 반환하기

●  선택한 일정과 댓글이 DB에 저장되어 있어야 합니다.

⚠️ 예외 처리

● 선택한 일정이나 댓글의 ID를 입력받지 않은 경우

● 일정이나 댓글이 DB에 저장되지 않은 경우

● 선택한 댓글의 사용자가 현재 사용자와 일치하지 않은 경우

    @DeleteMapping("/{id}")
    public ResponseEntity<CommonResponse<Void>> deleteComment(@PathVariable Long id, @RequestBody DeleteCommentRequestDto deleteCommentRequestDto) {
        try {
            commentService.deleteComment(id, deleteCommentRequestDto);
            return ResponseEntity.ok(
                    CommonResponse.<Void>builder()
                            .statusCode(HttpStatus.OK.value())
                            .msg("댓글이 성공적으로 삭제되었습니다.")
                            .build()
            );
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(
                    CommonResponse.<Void>builder()
                            .statusCode(HttpStatus.BAD_REQUEST.value())
                            .msg(e.getMessage())
                            .build()
            );
        }
    }

//CommentController

@DeleteMapping("/{id}")을 사용하여 /api/comments/{id} 경로로 들어오는 DELETE 요청을 처리

댓글을 삭제하려는 요청을 받아서 CommentService를 통해 댓글을 삭제

@Getter
public class DeleteCommentRequestDto {
    private String userId;

    public void validate() {
        if (userId == null || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("사용자 ID가 비어 있습니다.");
        }
    }
}

//DeleteCommentRequestDto

DeleteCommentRequestDto는 댓글 삭제 요청을 담는다

    public void deleteComment(Long id, DeleteCommentRequestDto deleteCommentRequestDto) {
        Comment comment = commentRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("댓글이 존재하지 않습니다"));

        if (!comment.getUserId().equals(deleteCommentRequestDto.getUserId())) {
            throw new IllegalArgumentException("댓글 작성자와 현재 사용자 불일치");
        }

        commentRepository.delete(comment);
    }

//CommentService

댓글 삭제 요청을 처리

일치하면 댓글 삭제

'TIL' 카테고리의 다른 글

TIL - 2024/06/03  (0) 2024.06.03
TIL - 2024/05/31  (0) 2024.05.31
TIL - 2024/05/29  (2) 2024.05.29
TIL - 2024/05/28  (0) 2024.05.28
TIL - 2024/05/27  (0) 2024.05.27
  1. 2️⃣단계 댓글 등록
  2. 기능
  3. 조건
  4. ⚠️ 예외 처리
  5. 전체적인 흐름
  6. 3️⃣단계 댓글 수정
  7. 기능
  8. 조건
  9. ⚠️ 예외 처리
  10. 4️⃣단계 댓글 삭제
  11. 기능
  12. 조건
  13. ⚠️ 예외 처리
'TIL' 카테고리의 다른 글
  • TIL - 2024/06/03
  • TIL - 2024/05/31
  • TIL - 2024/05/29
  • TIL - 2024/05/28
기석김
기석김
깃허브: https://github.com/kiseokkm
기석김
김기석
기석김
전체
오늘
어제
  • 분류 전체보기 (140)
    • 클라우드 (1)
    • 네트워크 (5)
    • Github&Git (8)
    • CS (2)
    • 스터디 (1)
    • Spring (1)
    • 코딩테스트 (20)
      • Java (6)
      • Mysql (12)
      • Python (2)
    • TIL (93)
    • Intellij (2)
    • 회고 (5)
    • DB (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 내일배움캠프
  • http
  • 스파르타내일배움캠프TIL
  • MySQL
  • db
  • bare clone
  • mirror push
  • til
  • SQL
  • where
  • github
  • 프로그래머스
  • intellij
  • Java
  • From
  • 개발자질문
  • 스파르타내일배움캠프
  • select
  • fork 잔디
  • Git

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.3.0
기석김
TIL - 2024/05/30
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.