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

♻️ change package for category recipe search #112

Merged
merged 3 commits into from
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from all 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

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,11 @@ public class CategoryService {

private final CategoryRepository categoryRepository;
private final CategoryRecipeRepository categoryRecipeRepository;
private final RecipeRepository recipeRepository;
private final RecipeService recipeService;

public void saveCategories(Recipe recipe, List<String> categories) {
categories.forEach(category -> saveCategoryRecipe(recipe, category));
}

public List<MainRecipeResponse> readRecipesOfCategory(RecipeOfCategoryRequest request) {
String categoryName = request.category();
Pageable pageable = PageRequest.of(request.pageNumber(), request.pageSize());
List<Long> recipeIds = categoryRecipeRepository.findRecipeIdsByCategoryName(categoryName, pageable);

List<RecipeDataResponse> recipeDataResponses = recipeRepository.findRecipeData(recipeIds);
return recipeService.convertToMainRecipeResponses(recipeDataResponses);
}

private void saveCategoryRecipe(Recipe recipe, String name) {
Category category = categoryRepository.findByName(name)
.orElseGet(() -> categoryRepository.save(new Category(name)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import java.util.List;
import lombok.RequiredArgsConstructor;
import net.pengcook.category.dto.RecipeOfCategoryRequest;
import net.pengcook.recipe.dto.MainRecipeResponse;
import net.pengcook.recipe.dto.RecipeStepResponse;
import net.pengcook.recipe.service.RecipeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
Expand All @@ -27,4 +29,9 @@ public List<MainRecipeResponse> readRecipes(@RequestParam int pageNumber, @Reque
public List<RecipeStepResponse> readRecipeSteps(@PathVariable long id) {
return recipeService.readRecipeSteps(id);
}

@GetMapping("/search")
public List<MainRecipeResponse> readRecipesOfCategory(@ModelAttribute RecipeOfCategoryRequest request) {
Copy link
Contributor

Choose a reason for hiding this comment

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

이제 슬슬 해당 DTO 안에 validation 을 추가하는 것은 어떠신가요~?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

지금 새로 이슈 파놓고 댓글 완성되면 바로 진행해보겠습니다

return recipeService.readRecipesOfCategory(request);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import net.pengcook.category.dto.RecipeOfCategoryRequest;
import net.pengcook.category.repository.CategoryRecipeRepository;
import net.pengcook.recipe.domain.RecipeStep;
import net.pengcook.recipe.dto.AuthorResponse;
import net.pengcook.recipe.dto.CategoryResponse;
Expand All @@ -24,6 +26,7 @@ public class RecipeService {

private final RecipeRepository recipeRepository;
private final RecipeStepRepository recipeStepRepository;
private final CategoryRecipeRepository categoryRecipeRepository;

public List<MainRecipeResponse> readRecipes(int pageNumber, int pageSize) {
Pageable pageable = PageRequest.of(pageNumber, pageSize);
Expand All @@ -38,13 +41,22 @@ public List<RecipeStepResponse> readRecipeSteps(long id) {
return convertToRecipeStepResponses(recipeSteps);
}

public List<MainRecipeResponse> readRecipesOfCategory(RecipeOfCategoryRequest request) {
String categoryName = request.category();
Pageable pageable = PageRequest.of(request.pageNumber(), request.pageSize());
List<Long> recipeIds = categoryRecipeRepository.findRecipeIdsByCategoryName(categoryName, pageable);

List<RecipeDataResponse> recipeDataResponses = recipeRepository.findRecipeData(recipeIds);
return convertToMainRecipeResponses(recipeDataResponses);

Choose a reason for hiding this comment

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

카테고리별 조회 로직이 recipe 패키지에 포함돼서 convert 메서드 접근제어자는 다시 private로 바꾸면 좋을 것 같습니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

좋은 생각이에요!!

}

private List<RecipeStepResponse> convertToRecipeStepResponses(List<RecipeStep> recipeSteps) {
return recipeSteps.stream()
.map(RecipeStepResponse::new)
.toList();
}

public List<MainRecipeResponse> convertToMainRecipeResponses(List<RecipeDataResponse> recipeDataResponses) {
private List<MainRecipeResponse> convertToMainRecipeResponses(List<RecipeDataResponse> recipeDataResponses) {
Collection<List<RecipeDataResponse>> groupedRecipeData = recipeDataResponses.stream()
.collect(Collectors.groupingBy(RecipeDataResponse::recipeId))
.values();
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,13 @@
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Stream;
import net.pengcook.category.dto.RecipeOfCategoryRequest;
import net.pengcook.category.repository.CategoryRecipeRepository;
import net.pengcook.category.repository.CategoryRepository;
import net.pengcook.recipe.domain.Recipe;
import net.pengcook.recipe.dto.MainRecipeResponse;
import net.pengcook.recipe.service.RecipeService;
import net.pengcook.user.domain.User;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
Expand Down Expand Up @@ -52,27 +46,4 @@ void saveCategories() {
() -> assertThat(categoryRecipeRepository.count()).isEqualTo(INITIAL_CATEGORY_RECIPE_COUNT + 2)
);
}

@ParameterizedTest
@MethodSource("provideParameters")
@DisplayName("특정 카테고리의 레시피를 찾는다.")
void readRecipesOfCategory(int pageNumber, int pageSize, List<Long> expected) {
RecipeOfCategoryRequest request = new RecipeOfCategoryRequest("한식", pageNumber, pageSize);

List<MainRecipeResponse> mainRecipeResponses = categoryService.readRecipesOfCategory(request);
List<Long> actual = mainRecipeResponses.stream().map(MainRecipeResponse::recipeId).toList();

assertAll(
() -> assertThat(actual.size()).isEqualTo(pageSize),
() -> assertThat(actual).containsAll(expected)
);
}

static Stream<Arguments> provideParameters() {
return Stream.of(
Arguments.of(0, 2, List.of(2L, 3L)),
Arguments.of(1, 2, List.of(7L, 9L)),
Arguments.of(1, 3, List.of(9L, 14L, 15L))
);
}
}
Original file line number Diff line number Diff line change
@@ -1,28 +1,21 @@
package net.pengcook.recipe.controller;

import static com.epages.restdocs.apispec.RestAssuredRestDocumentationWrapper.document;
import static org.hamcrest.Matchers.is;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.queryParameters;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.BeforeEach;
import net.pengcook.RestDocsSetting;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.jdbc.Sql;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@Sql(value = "/data/recipe.sql")
class RecipeControllerTest {

@LocalServerPort
private int port;

@BeforeEach
void setUp() {
RestAssured.port = port;
}
class RecipeControllerTest extends RestDocsSetting {

@Test
@DisplayName("레시피 개요 목록을 조회한다.")
Expand All @@ -45,4 +38,43 @@ void readRecipeSteps() {
.then().log().all()
.body("size()", is(3));
}

@Test
@DisplayName("카테고리별 레시피 개요 목록을 조회한다.")
void readRecipesOfCategory() {
RestAssured.given(spec).log().all()
.filter(document(DEFAULT_RESTDOCS_PATH,
queryParameters(
parameterWithName("category").description("카테고리"),
parameterWithName("pageNumber").description("페이지 번호"),
parameterWithName("pageSize").description("페이지 크기")
),
responseFields(
fieldWithPath("[]").description("레시피 목록"),
fieldWithPath("[].recipeId").description("레시피 아이디"),
fieldWithPath("[].title").description("레시피 제목"),
fieldWithPath("[].author").description("작성자 정보"),
fieldWithPath("[].author.authorId").description("작성자 아이디"),
fieldWithPath("[].author.authorName").description("작성자 이름"),
fieldWithPath("[].author.authorImage").description("작성자 이미지"),
fieldWithPath("[].cookingTime").description("조리 시간"),
fieldWithPath("[].thumbnail").description("썸네일 이미지"),
fieldWithPath("[].difficulty").description("난이도"),
fieldWithPath("[].likeCount").description("좋아요 수"),
fieldWithPath("[].description").description("레시피 설명"),
fieldWithPath("[].category").description("카테고리 목록"),
fieldWithPath("[].category[].categoryId").description("카테고리 아이디"),
fieldWithPath("[].category[].categoryName").description("카테고리 이름"),
fieldWithPath("[].ingredient").description("재료 목록"),
fieldWithPath("[].ingredient[].ingredientId").description("재료 아이디"),
fieldWithPath("[].ingredient[].ingredientName").description("재료 이름"),
fieldWithPath("[].ingredient[].requirement").description("재료 필수 여부")
)))
.queryParam("category", "한식")
.queryParam("pageNumber", 0)
.queryParam("pageSize", 3)
.when().get("/api/recipes/search")
.then().log().all()
.body("size()", is(3));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,21 @@ void findRecipeIds() {

List<Long> recipeIds = repository.findRecipeIds(pageable);

assertThat(recipeIds).containsExactly(4L, 3L, 2L);
assertThat(recipeIds).containsExactly(15L, 14L, 13L);
}

@Test
@DisplayName("레시피 id에 해당되는 세부 정보를 반환한다.")
void findRecipeData() {
List<Long> recipeIds = List.of(4L, 3L);
RecipeDataResponse expectedData = new RecipeDataResponse(4, "흰쌀밥", 1, "loki", "loki.jpg", LocalTime.of(0, 40),
"흰쌀밥이미지.jpg", 2, 4, "흰쌀밥 조리법", 3, "채식", 2, "쌀", REQUIRED
RecipeDataResponse expectedData = new RecipeDataResponse(4, "토마토스파게티", 1, "loki", "loki.jpg", LocalTime.of(0, 30),
"토마토스파게티이미지.jpg", 3, 2, "토마토스파게티 조리법", 2, "양식", 2, "쌀", REQUIRED
);

List<RecipeDataResponse> recipeData = repository.findRecipeData(recipeIds);

assertAll(
() -> assertThat(recipeData).hasSize(8),
() -> assertThat(recipeData).hasSize(6 + 3),

Choose a reason for hiding this comment

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

제가 작성했던 부분이지만 다시 봐도 검증 방식이 애매하긴 하네요. 🥲 데이터 가져오는 방식이나 쿼리문을 향후 개선하기는 해야할 것 같습니다!
데이터 수정하시느라 고생 많으셨어요.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

해석하느라 초큼 힘들었습니다
하지만 잠깐 들여다보면 알아볼 수 있는 정도기는 했어요~~~

() -> assertThat(recipeData).contains(expectedData)
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
package net.pengcook.recipe.service;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import net.pengcook.category.dto.RecipeOfCategoryRequest;
import net.pengcook.recipe.dto.MainRecipeResponse;
import net.pengcook.recipe.dto.RecipeStepResponse;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
Expand All @@ -24,7 +29,7 @@ class RecipeServiceTest {
private RecipeService recipeService;

@ParameterizedTest
@CsvSource(value = {"0,2,4", "1,2,2", "1,3,1"})
@CsvSource(value = {"0,2,15", "1,2,13", "1,3,12"})
@DisplayName("요청받은 페이지의 레시피 개요 목록을 조회한다.")
void readRecipes(int pageNumber, int pageSize, int expectedFirstRecipeId) {
List<MainRecipeResponse> mainRecipeResponses = recipeService.readRecipes(pageNumber, pageSize);
Expand All @@ -46,4 +51,27 @@ void readRecipeSteps() {

assertThat(recipeStepResponses).isEqualTo(expectedRecipeStepResponses);
}

@ParameterizedTest
@MethodSource("provideParameters")
@DisplayName("특정 카테고리의 레시피를 찾는다.")
void readRecipesOfCategory(int pageNumber, int pageSize, List<Long> expected) {
RecipeOfCategoryRequest request = new RecipeOfCategoryRequest("한식", pageNumber, pageSize);

List<MainRecipeResponse> mainRecipeResponses = recipeService.readRecipesOfCategory(request);
List<Long> actual = mainRecipeResponses.stream().map(MainRecipeResponse::recipeId).toList();

assertAll(
() -> assertThat(actual.size()).isEqualTo(pageSize),
() -> assertThat(actual).containsAll(expected)
);
}

static Stream<Arguments> provideParameters() {
return Stream.of(
Arguments.of(0, 2, List.of(2L, 3L)),
Arguments.of(1, 2, List.of(7L, 9L)),
Arguments.of(1, 3, List.of(9L, 14L, 15L))
);
}
}
Loading
Loading