jnk1m
Foliage IT
jnk1m
전체 방문자
오늘
어제
  • 분류 전체보기 (209)
    • Today I Learned (34)
    • Java (47)
    • Database (15)
    • [NHN Academy] (27)
    • Spring (47)
    • HTML + CSS + JavaScript (11)
    • JSP (3)
    • Node.js (10)
    • React Native (2)
    • 기타 (8)
    • 스크랩 (5)

인기 글

최근 글

티스토리

hELLO · Designed By 정상우.
글쓰기 / 관리자
jnk1m

Foliage IT

Today I Learned

[TIL] 23/10/5 뷰를 이용한 MenuController 리팩토링 (getMenusInCategory)

2023. 10. 5. 19:32
 

[TIL] 23/8/18 Category 테이블 View 추가 + 뷰 생성법, 사용법, Spring boot entity 작성

문제점 처음 서비스를 기획하며 데이터베이스를 설계했을 때 생각치 못했던 문제점들이 프로젝트가 진행되며 드러나기 시작했다. 카테고리를 관리하는 category 테이블이 있다. 이 테이블은 메뉴

foliageit.tistory.com

위 글에서 얘기했던 것과 같이 현재 카테고리 테이블엔 메뉴를 위한 카테고리와 옵션을 위한 카테고리가 혼재되어 있다.

기존 코드에서는 하드 코딩하여 카테고리 아이디가 8이거나, 10보다 크거나 같을 경우에 에러를 던졌다. 

    // Categories 8, 10, and 11 are not in use due to menu consolidation.
    // Starting from ID 12, they are not used for menu retrieval.
    // Exception is thrown if the category ID is 8 or greater than or equal to 10.
    if (categoryId >= 10 || categoryId == 8) {
      throw new InvalidCategoryIdException("Invalid Category");
    }

유연성이 떨어졌던 기존 코드.

하지만 이제는 뷰가 있으니 하드코딩할 필요가 없다~

 

@Override
  public List<Integer> getAllMenuCategoryIds() {
    List<Integer> categoryIds = new ArrayList<>();
    List<MenuCategoryView> menuCategoryViews = menuCategoryViewRepository.findAll();
    for (MenuCategoryView menuCategoryView : menuCategoryViews) {
      categoryIds.add(menuCategoryView.getCategoryId());
    }
    return categoryIds;
  }

먼저 메뉴 카테고리 뷰를 가져와서 리스트에 메뉴 카테고리의 아이디만 리스트에 담았다.

 

@GetMapping("/{categoryId}")
  public String getMenusInCategory(@PathVariable int categoryId, Model model){
    List<Integer> allMenuCategoryIds = categoryService.getAllMenuCategoryIds();

    Category category;
    List<MenuDTO> menuDTOList;

    if (allMenuCategoryIds.contains(categoryId)) {
      category = categoryService.findCategory(categoryId);
      menuDTOList = menuService.getMenusInCategory(category);

    } else {
      category = null;
      menuDTOList = Collections.emptyList();
    }

    model.addAttribute("category", category);
    model.addAttribute("menus", menuDTOList);
    return "menu-list";
  }

먼저 파라미터로 받은 카테고리 아이디가 allMenuCategoryIds 리스트에 들어있는 항목인지 검증한다.

메뉴에 속한 카테고리가 맞다면, 카테고리 객체를 가져오고 해당 카테고리에 속한 메뉴를 전부 가져온다.

아닌 경우에는 category는 null, menuDTOList는 emptyList로 넘겨준다.

이 경우, 프론트에서 NP가 발생하지 않도록 NP 체크가 필수다.


Java ArrayList contains 메서드 👇

    /**
     * Returns {@code true} if this list contains the specified element.
     * More formally, returns {@code true} if and only if this list contains
     * at least one element {@code e} such that
     * {@code Objects.equals(o, e)}.
     *
     * @param o element whose presence in this list is to be tested
     * @return {@code true} if this list contains the specified element
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

 

    'Today I Learned' 카테고리의 다른 글
    • [TIL] 23/9/27 Google 외부 애플리케이션 부하 분산기 관련 문제 해결문서
    • [TIL] 23/9/25 Google OAuth Sign in authorization_request_not_found 에러 여정기 1
    • [TIL] 23/9/22 Google OAuth Sign in authorization_request_not_found 에러 (로드밸런서 스티키 세션 설정 자세히)
    • [TIL] 23/9/13 메뉴 디테일 수정하기 구현

    티스토리툴바