Spring/[P] 눈치우기 봉사활동 매칭 플랫폼

게시글 댓글 작성하기 (대댓글X)

alsruds 2024. 2. 16. 22:55

 

클라이언트 서버에서 전송한 게시글 댓글 데이터를 DB 에 저장

 

☃️ Controller

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

    // 봉사활동글 댓글 추가
    @PostMapping("/volunteer")
    public ResponseEntity<Void> addCommentVolunteer(CommentSaveRequest request) throws IOException {
        commentService.addCommentVolunteer(request);
        return new ResponseEntity(HttpStatus.OK);
    }
}

 

· 전송받은 댓글 데이터 service 로직으로 넘겨주기

 

☃️ Service

@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class CommentService {
    private final CommentVolunteerRepository commentVolunteerRepository;
    private final UserRepository userRepository;
    private final VolunteerRepository volunteerRepository;

    // 봉사활동글 댓글 추가
    public void addCommentVolunteer(CommentSaveRequest request) throws IOException {
        User user =  getUserOrThrow(request.getUserId());
        Volunteer volunteer = getVolunteerOrThrow(request.getPostId());
        CommentVolunteer commentVolunteer = CommentVolunteer.createCommentVolunteer(user, volunteer, request.getContent());
        commentVolunteerRepository.save(commentVolunteer);
    }

    // 예외 처리 - 존재하는 User 인가
    private User getUserOrThrow(Long userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_USER));
    }

    // 예외 처리 - 존재하는 Volunteer 인가
    private Volunteer getVolunteerOrThrow(Long volunteerId) {
        return volunteerRepository.findById(volunteerId)
                .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_VOLUNTEER));
    }
}

 

· 해당 사용자와 게시글 존재 유무 확인 후 저장하기

 

☃️ Repository

public interface CommentVolunteerRepository extends JpaRepository<CommentVolunteer, Long> {
    List<CommentVolunteer> findByUserIdAndVolunteerId(Long userId, Long volunteerId);
}
public interface UserRepository extends JpaRepository<User, Long> {}
public interface VolunteerRepository extends JpaRepository<Volunteer, Long> {}

 

☃️ Dto

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class CommentSaveRequest {
    private Long userId;
    private Long postId;
    private String content;
}