오늘은 카드의 CRUD 기능 구현과 보관/복구를 목표로 하고, 남은 시간 이동을 구현해볼 생각이다.
CRUD 기능은 덱과 큰 차이점은 없었으나 다른점이 있다면 필드의 개수가 덱보다 훨씬 많아 requestDto나 responseDto, entity에 Builder 기능을 더 적극 채용했다는 점 뿐이다.
또한 patch 기능을 적극 활용하기 위해 하나의 메서드에서 제목과 설명 중 하나만 수정할 수 있도록 하기 위해 아래와 같이 로직을 짰다.
@Transactional
public void editCard(Long id, CardEditRequestDto requestDto) {
Card card = findCardById(id);
if (requestDto.getTitle() != null) card.editTitle(requestDto.getTitle());
if (requestDto.getDescription() != null) card.editDescription(requestDto.getDescription());
}
보관/복구는 이전에 비슷한 기능을 구현한 경험이 있어 비교적 원만하게 구현에 성공하였다.
이동에 대해서는 구현 전에는 board_id도 수정해야 했는데 외래키를 수정한 경험이 없어 걱정을 많이 했으나 외래키를 직접 수정하는 것이 아닌 연관관계를 새로 만든다는 개념으로 접근했더니 의외로 쉽게 구현이 되었다.
@Transactional
public void moveCard(Long id, MoveCardRequestDto requestDto) {
Card card = findCardById(id);
Deck deck = findDeckById(requestDto.getDeckId());
Card prev = cardRepository.findById(requestDto.getPrevCardId()).orElse(null);
Card next = cardRepository.findById(requestDto.getNextCardId()).orElse(null);
if (requestDto.getDeckId() != null) card.moveToDeck(deck);
if (prev != null && next != null) { // 두 카드 사이로 옮길 때
card.editPosition((prev.getPosition() + next.getPosition()) / 2f);
} else if (prev == null) { // 맨 처음으로 옮길 때
card.editPosition(next.getPosition() / 2f);
} else { // 맨 마지막으로 옮길 때
card.editPosition(prev.getPosition() + CYCLE);
}
}
이미지 업로드까지 구현을 마쳤다.