본문 바로가기
TIL

항해99_TIL220603 (배열 저장)

by Hyeongjun_Ham 2022. 6. 3.

오늘 새로운 주차 시작했다.

과제가 한 두개씩 풀리니 기분이 상당히 업 됐다.

 

오늘 고생한 것

 

@PostMapping("/restaurant/{restaurantId}/food/register") // 받아오는 것 자체를 리스트로 받아버린다.
public ResponseEntity registerFood(@PathVariable Long restaurantId, @RequestBody List<FoodRequestDto> requestDto) {
    //가게 있는지 체크
    restaurantRepository.findById(restaurantId).orElseThrow(
            () -> new IllegalArgumentException("가게가 존재하지 않습니다.")
    );
    for (FoodRequestDto foodRequestDto : requestDto) {
        //메뉴이름, 가격 유효성 체크
        foodService.registerFood(restaurantId, foodRequestDto);

        Food food = new Food(restaurantId, foodRequestDto);

        foodRepository.save(food);
    }
    return ResponseEntity.ok(requestDto);

}

 

 

public class FoodService {

    private final FoodRepository foodRepository;

    public void registerFood(Long restaurantId, FoodRequestDto requestDto) {

        validDuplicationMenu(restaurantId, requestDto);
        validPrice(requestDto);
    }

    //중복된 메뉴 체크
    public void validDuplicationMenu(Long restaurantId, FoodRequestDto requestDto) {
        List<Food> menu = foodRepository.findAllByRestaurantId(restaurantId);
        for (Food food : menu) {
            String checkDuple = food.getName();
            if (requestDto.getName().equals(checkDuple)) {
                throw new IllegalArgumentException("중복 된 메뉴가 있습니다.");
            }
        }
    }

    //가격 유효성 체크
    public void validPrice(FoodRequestDto requestDto) {
            Long price = requestDto.getPrice();
            if (price < 100 || price > 1000000) {
                throw new IllegalArgumentException("100원 ~ 1,000,000원 사이로 입력해주세요");
            } else if (price % 100 != 0) {
                throw new IllegalArgumentException("100원 단위로 입력해 주세요");
            }
    }

    // 메뉴 전체 보여주기
    public List<FoodResponseDto> showMenu(Long restaurantId) {
        return foodRepository.findAllByRestaurantId(restaurantId)
                .stream()
                .map(FoodResponseDto::new)
                .collect(Collectors.toList());
    }
}

 

 

{ restaurantId: 1 foods: [ { id: 1, quantity: 1 }, { id: 2, quantity: 2 }, { id: 3, quantity: 3 } ] }

받아 올때 이런식으로 배열을 받아서 어떻게 해야하나 고민좀 많이했다.

고민하다가 한번에 리스트로 받는 방법을 하니 쉽게 해결 됐다.

배열로 받는 것이 과제에서 원하는 것이라 이렇게 해결하면 됐는데, 정작 한개를 저장할 때는 작동안한다..

동시에 작동하게 하는 방법은 dto에 배열과 배열이 아닌걸 넣어놓고 if문으로 처리할 수 있지않을까.. 하는 생각이 갑자기든다.

 

일단 과제 다 끝내고 리팩토링해보자.

'TIL' 카테고리의 다른 글

항해99_WIL220605 (ORM, SQL, MVC)  (0) 2022.06.05
항해99_TIL220604 (트랜잭션)  (0) 2022.06.04
항해99_TIL220602 (테스트 코드)  (0) 2022.06.02
항해99_TIL220601 (연관관계 매핑)  (0) 2022.06.02
항해99_TIL220531 (Builder)  (0) 2022.05.31