Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 특정 여행 상세 삭제 API 구현 #24 #72

Merged
merged 6 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
Expand Down Expand Up @@ -51,4 +52,12 @@ public ResponseEntity<Void> updateTravel(
travelService.updateTravel(travelRequest, travelId);
return ResponseEntity.ok().build();
}

@DeleteMapping("/{travelId}")
public ResponseEntity<Void> deleteTravel(
@PathVariable @Min(value = 1L, message = "여행 식별자는 양수로 이루어져야 합니다.") Long travelId,
@MemberId Long memberId) {
travelService.deleteTravel(travelId);
return ResponseEntity.ok().build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,13 @@ private TravelResponses getTravelDetailResponses(List<TravelMember> travelMember
.toList();
return TravelResponses.from(travels);
}

@Transactional
public void deleteTravel(Long travelId) {
if (!visitRepository.findAllByTravelId(travelId).isEmpty()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

existsByTravelId를 만드는 건 어떨까요?
그리고 해당 검증 부분은 메서드를 분리하면 좋을 것 같아요!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

existsByTravelId를 사용하는 것은 좋은 아이디어인 것 같아요. 그런데 여기서도 논리적 삭제를 고려해야 할 것 같네요!
boolean existsByTravelIdAndIsDeletedFalse(Long travelId);

throw new StaccatoException("해당 여행 상세에 방문 기록이 남아있어 삭제할 수 없습니다.");
}
visitRepository.deleteByTravelId(travelId);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

visit이 삭제되었을 때 visitImagevisitLog도 함께 삭제되어야 할 것 같은데요, 이 부분은 팀원들과 얘기해봐야 할 것 같네요..!

travelRepository.deleteById(travelId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.staccato.visit.domain.Visit;

public interface VisitRepository extends JpaRepository<Visit, Long> {
List<Visit> findAllByTravelId(Long travelId);

@Modifying(clearAutomatically = true)
@Query("UPDATE Visit vi SET vi.isDeleted = true WHERE vi.travel.id = :travelId")
void deleteByTravelId(@Param("travelId") Long travelId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
Expand Down Expand Up @@ -226,4 +227,21 @@ private TravelRequest createTravelRequest(int year) {
LocalDate.of(year, 7, 1),
LocalDate.of(year, 7, 10));
}

@DisplayName("사용자가 여행 상세 삭제를 요청하면, 여행 상세를 삭제한다.")
@Test
void deleteTravel() {
// given
Long travelId = 1L;
TravelRequest travelRequest = new TravelRequest("https://example.com/travels/geumohrm.jpg", "2023 여름 휴가", "친구들과 함께한 여름 휴가 여행", LocalDate.of(2023, 7, 1), LocalDate.of(2023, 7, 10));
createTravel(travelRequest);

// when & then
RestAssured.given().pathParam("travelId", travelId).log().all()
.header(HttpHeaders.AUTHORIZATION, USER_AUTHORIZATION)
.contentType(ContentType.JSON)
.when().delete("/travels/{travelId}")
.then().log().all()
.assertThat().statusCode(HttpStatus.OK.value());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ void withinDuration() {

@DisplayName("여행 상세를 수정 시 기존 방문 기록 날짜를 포함하지 않는 경우 수정에 실패한다.")
@Test
void validateDuration(){
void validateDuration() {
// given
Travel travel = Travel.builder()
.title("2023 여름 여행")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,16 @@
import com.staccato.exception.StaccatoException;
import com.staccato.member.domain.Member;
import com.staccato.member.repository.MemberRepository;
import com.staccato.pin.domain.Pin;
import com.staccato.pin.repository.PinRepository;
import com.staccato.travel.domain.Travel;
import com.staccato.travel.domain.TravelMember;
import com.staccato.travel.repository.TravelMemberRepository;
import com.staccato.travel.repository.TravelRepository;
import com.staccato.travel.service.dto.request.TravelRequest;
import com.staccato.travel.service.dto.response.TravelResponses;
import com.staccato.visit.domain.Visit;
import com.staccato.visit.repository.VisitRepository;

class TravelServiceTest extends ServiceSliceTest {
@Autowired
Expand All @@ -34,6 +38,10 @@ class TravelServiceTest extends ServiceSliceTest {
private TravelMemberRepository travelMemberRepository;
@Autowired
private TravelRepository travelRepository;
@Autowired
private VisitRepository visitRepository;
@Autowired
private PinRepository pinRepository;

static Stream<Arguments> yearProvider() {
return Stream.of(
Expand Down Expand Up @@ -90,15 +98,8 @@ private static TravelRequest createTravelRequest(int year) {
@Test
void updateTravel() {
// given
Long travelId = 1L;
Travel originTravel = new Travel(
"https://example.com/travels/geumohrm.jpg",
"2023 여름 휴가",
"친구들과 함께한 여름 휴가 여행",
LocalDate.of(2023, 7, 1),
LocalDate.of(2023, 7, 10)
);
travelRepository.save(originTravel);
Travel travel = createAndSaveTravel(2023);
Long travelId = travel.getId();
TravelRequest updatedTravel = new TravelRequest(
"https://example.com/travels/geumohrm.jpg",
"2023 신나는 여름 휴가",
Expand All @@ -109,33 +110,66 @@ void updateTravel() {

// when
travelService.updateTravel(updatedTravel, travelId);
Travel travel = travelRepository.findById(travelId).get();
Travel foundedTravel = travelRepository.findById(travelId).get();

// then
assertAll(
() -> assertThat(travel.getId()).isEqualTo(travelId),
() -> assertThat(travel.getTitle()).isEqualTo(updatedTravel.travelTitle()),
() -> assertThat(travel.getDescription()).isEqualTo(updatedTravel.description()),
() -> assertThat(travel.getStartAt()).isEqualTo(updatedTravel.startAt()),
() -> assertThat(travel.getEndAt()).isEqualTo(updatedTravel.endAt())
() -> assertThat(foundedTravel.getId()).isEqualTo(travelId),
() -> assertThat(foundedTravel.getTitle()).isEqualTo(updatedTravel.travelTitle()),
() -> assertThat(foundedTravel.getDescription()).isEqualTo(updatedTravel.description()),
() -> assertThat(foundedTravel.getStartAt()).isEqualTo(updatedTravel.startAt()),
() -> assertThat(foundedTravel.getEndAt()).isEqualTo(updatedTravel.endAt())
);
}

private Travel createAndSaveTravel(int year) {
Travel travel = new Travel(
"https://example.com/travels/geumohrm.jpg",
year + " 여름 휴가",
"친구들과 함께한 여름 휴가 여행",
LocalDate.of(year, 7, 1),
LocalDate.of(year, 7, 10)
);
return travelRepository.save(travel);
}

@DisplayName("존재하지 않는 여행 상세를 수정하려 할 경우 예외가 발생한다.")
@Test
void failUpdateTravel() {
// given
TravelRequest travelRequest = new TravelRequest(
"https://example.com/travels/geumohrm.jpg",
"2023 여름 휴가",
"친구들과 함께한 여름 휴가 여행",
LocalDate.of(2023, 7, 1),
LocalDate.of(2023, 7, 10)
);
TravelRequest travelRequest = createTravelRequest(2023);

// when & then
assertThatThrownBy(() -> travelService.updateTravel(travelRequest, 1L))
.isInstanceOf(StaccatoException.class)
.hasMessage("요청하신 여행을 찾을 수 없어요.");
}

@DisplayName("여행 식별값을 통해 여행 상세를 삭제한다.")
@Test
void deleteTravel() {
// given
Travel travel = createAndSaveTravel(2023);

// when
travelService.deleteTravel(travel.getId());

// then
Travel foundTravel = travelRepository.findById(travel.getId()).get();
assertThat(foundTravel.getIsDeleted()).isTrue();
}

@DisplayName("방문기록이 존재하는 여행 상세에 삭제를 시도할 경우 예외가 발생한다.")
@Test
void failDeleteTravel() {
// given
Travel travel = createAndSaveTravel(2023);
Pin pin = pinRepository.save(Pin.builder().place("Sample Place").address("Sample Address").build());
visitRepository.save(Visit.builder().visitedAt(LocalDate.now()).pin(pin).travel(travel).build());

// when & then
assertThatThrownBy(() -> travelService.deleteTravel(travel.getId()))
.isInstanceOf(StaccatoException.class)
.hasMessage("해당 여행 상세에 방문 기록이 남아있어 삭제할 수 없습니다.");
}
}