Skip to content

Commit

Permalink
[BE] feat: 축제 조회 필터링 구현(#602) (#603)
Browse files Browse the repository at this point in the history
* feat: specification 정의

* feat: FestivalFilter 정의

* feat: 축제 진행 상태에 따른 Controller, Service 생성

* refactor: private 생성자를 lombok 을 통해 생성

* chore: 괄호 제거

* chore: 변수 상수화

* chore: given 절 타입 명시

* feat: 축제 조회 ALL 삭제 및 기본값을 진행 중으로 변경

* feat: 축제 당일이 Progress에 포함되도록 변경 및 Spec 리팩터링

* feat: 축제 진행 상황별 정렬 조건 추가

* chore: 메서드 순서 변경

* chore: index 추가

* chore: 에러 메시지 변경

* chore: test 개행 변경 및 변수 재활용
  • Loading branch information
BGuga authored and seokjin8678 committed Nov 16, 2023
1 parent 6288aff commit 5e1f8df
Show file tree
Hide file tree
Showing 11 changed files with 322 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public enum ErrorCode {
DELETE_CONSTRAINT_STAGE("티켓이 등록된 공연은 삭제할 수 없습니다."),
DELETE_CONSTRAINT_SCHOOL("학생 또는 축제에 등록된 학교는 삭제할 수 없습니다."),
DUPLICATE_SCHOOL("이미 존재하는 학교 정보입니다."),
INVALID_FESTIVAL_FILTER("유효하지 않은 축제의 필터 값입니다."),


// 401
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.festago.festival.dto.FestivalResponse;
import com.festago.festival.dto.FestivalUpdateRequest;
import com.festago.festival.dto.FestivalsResponse;
import com.festago.festival.repository.FestivalFilter;
import com.festago.festival.repository.FestivalRepository;
import com.festago.school.domain.School;
import com.festago.school.repository.SchoolRepository;
Expand All @@ -19,8 +20,8 @@
import java.time.Clock;
import java.time.LocalDate;
import java.util.List;
import org.springframework.dao.DataIntegrityViolationException;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand Down Expand Up @@ -49,8 +50,8 @@ private void validate(Festival festival) {
}

@Transactional(readOnly = true)
public FestivalsResponse findAll() {
List<Festival> festivals = festivalRepository.findAll();
public FestivalsResponse findFestivals(FestivalFilter festivalFilter) {
List<Festival> festivals = festivalRepository.findAll(festivalFilter.getSpecification(LocalDate.now(clock)));
return FestivalsResponse.from(festivals);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.festago.festival.repository;

import com.festago.common.exception.BadRequestException;
import com.festago.common.exception.ErrorCode;
import com.festago.festival.domain.Festival;
import java.time.LocalDate;
import java.util.function.Function;
import org.springframework.data.jpa.domain.Specification;

public enum FestivalFilter {
PROGRESS(FestivalSpecification::progress),
PLANNED(FestivalSpecification::planned),
END(FestivalSpecification::end);

private final Function<LocalDate, Specification<Festival>> filter;

FestivalFilter(Function<LocalDate, Specification<Festival>> filter) {
this.filter = filter;
}

public static FestivalFilter from(String filterName) {
return switch (filterName.toUpperCase()) {
case "PROGRESS" -> PROGRESS;
case "PLANNED" -> PLANNED;
case "END" -> END;
default -> throw new BadRequestException(ErrorCode.INVALID_FESTIVAL_FILTER);
};
}

public Specification<Festival> getSpecification(LocalDate currentTime) {
return filter.apply(currentTime);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import com.festago.festival.domain.Festival;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface FestivalRepository extends JpaRepository<Festival, Long> {
public interface FestivalRepository extends JpaRepository<Festival, Long>, JpaSpecificationExecutor<Festival> {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.festago.festival.repository;

import com.festago.festival.domain.Festival;
import java.time.LocalDate;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.data.jpa.domain.Specification;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FestivalSpecification {

private static final String START_DATE = "startDate";
private static final String END_DATE = "endDate";

public static Specification<Festival> progress(LocalDate currentTime) {
return (root, query, criteriaBuilder) -> {
query.orderBy(criteriaBuilder.asc(root.get(START_DATE)));
return criteriaBuilder.and(
criteriaBuilder.lessThanOrEqualTo(root.get(START_DATE), currentTime),
criteriaBuilder.greaterThanOrEqualTo(root.get(END_DATE), currentTime)
);
};
}

public static Specification<Festival> planned(LocalDate currentTime) {
return (root, query, criteriaBuilder) -> {
query.orderBy(criteriaBuilder.asc(root.get(START_DATE)));
return criteriaBuilder.greaterThan(root.get(START_DATE), currentTime);
};
}

public static Specification<Festival> end(LocalDate currentTime) {
return (root, query, criteriaBuilder) -> {
query.orderBy(criteriaBuilder.desc(root.get(END_DATE)));
return criteriaBuilder.lessThan(root.get(END_DATE), currentTime);
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
import com.festago.festival.application.FestivalService;
import com.festago.festival.dto.FestivalDetailResponse;
import com.festago.festival.dto.FestivalsResponse;
import com.festago.festival.repository.FestivalFilter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
Expand All @@ -21,9 +23,10 @@ public class FestivalController {
private final FestivalService festivalService;

@GetMapping
@Operation(description = "모든 축제들을 조회한다.", summary = "축제 목록 조회")
public ResponseEntity<FestivalsResponse> findAll() {
FestivalsResponse response = festivalService.findAll();
@Operation(description = "축제를 조건별로 조회한다. PROGRESS: 진행 중, PLANNED: 진행 예정, END: 종료, 기본값 -> 진행 중", summary = "축제 목록 조회")
public ResponseEntity<FestivalsResponse> findFestivals(
@RequestParam(defaultValue = "PROGRESS") String festivalFilter) {
FestivalsResponse response = festivalService.findFestivals(FestivalFilter.from(festivalFilter));
return ResponseEntity.ok()
.body(response);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
create index festival_start_date_index
on festival (start_date);
create index festival_end_date_index
on festival (end_date desc);
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import com.festago.festival.dto.FestivalDetailResponse;
import com.festago.festival.dto.FestivalDetailStageResponse;
import com.festago.festival.dto.FestivalResponse;
import com.festago.festival.dto.FestivalsResponse;
import com.festago.festival.repository.FestivalRepository;
import com.festago.school.domain.School;
import com.festago.school.repository.SchoolRepository;
Expand Down Expand Up @@ -61,22 +60,6 @@ class FestivalServiceTest {
@InjectMocks
FestivalService festivalService;

@Test
void 모든_축제_조회() {
// given
Festival festival1 = FestivalFixture.festival().id(1L).build();
Festival festival2 = FestivalFixture.festival().id(2L).build();
given(festivalRepository.findAll()).willReturn(List.of(festival1, festival2));

// when
FestivalsResponse response = festivalService.findAll();

// then
List<Long> festivalIds = response.festivals().stream().map(FestivalResponse::id).toList();

assertThat(festivalIds).containsExactly(1L, 2L);
}

@Nested
class 축제_생성 {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.festago.festival.domain;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.festago.common.exception.BadRequestException;
import com.festago.festival.repository.FestivalFilter;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator.ReplaceUnderscores;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

@DisplayNameGeneration(ReplaceUnderscores.class)
@SuppressWarnings("NonAsciiCharacters")
class FestivalFilterTest {

@Test
void 유효하지_않은_name_이면_예외() {
// given && when && then
assertThatThrownBy(() -> FestivalFilter.from("unvalid"))
.isInstanceOf(BadRequestException.class);
}

@ValueSource(strings = {"progress", "Progress", "PROGRESS"})
@ParameterizedTest
void PROGRESS_반환(String value) {
// given && when
FestivalFilter filter = FestivalFilter.from(value);

// then
assertThat(filter).isEqualTo(FestivalFilter.PROGRESS);
}

@ValueSource(strings = {"planned", "Planned", "PLANNED"})
@ParameterizedTest
void PLANNED_반환(String value) {
// given && when
FestivalFilter filter = FestivalFilter.from(value);

// then
assertThat(filter).isEqualTo(FestivalFilter.PLANNED);
}

@ValueSource(strings = {"end", "End", "END"})
@ParameterizedTest
void END_반환(String value) {
// given && when
FestivalFilter filter = FestivalFilter.from(value);

// then
assertThat(filter).isEqualTo(FestivalFilter.END);
}
}
Loading

0 comments on commit 5e1f8df

Please sign in to comment.