Spring/[P] AI 기반 사용자 맞춤형 메뉴와 맛집 추천

[Springboot] 식사 기록 조회 개발하기

alsruds 2024. 8. 28. 12:33

📂 apiPayload

📂 config

📂 controller

  L MainController

📂 domain

  L 📂 common

  L 📂 enums

  L User

  L Food

📂 dto

  L 📂 request

  L 📂 response

        L MainHistoryResponseDto

📂 jwt

📂 repository

  L UserRepository

  L FoodRepository

📂 service

  L MainService

  L MainServiceImpl

 

 

날짜에 맞춰 등록된 식사 기록을 반환한다

 

① MainHistoryResponseDto : 반환하고자 하는 정보, 기본값 세팅

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MainHistoryResponseDto {
    int userTotalKcal;
    int userNowKcal;
    int userCarbo;
    int userProtein;
    int userFat;
    String breakfastName;
    int breakfastKcal;
    String lunchName;
    int lunchKcal;
    String dinnerName;
    int dinnerKcal;

    public static MainHistoryResponseDto mainHistoryResponse(User user, List<Food> foodList) {
        // 영양소 및 식사 정보 초기화 (저장된 기록이 없을 수도 있음)
        int totalCarbo = 0, totalProtein = 0, totalFat = 0, totalKcal = 0;
        String breakfastName = null, lunchName = null, dinnerName = null;
        int breakfastKcal = 0, lunchKcal = 0, dinnerKcal = 0;

        for (Food food : foodList) {
            int foodKcal = (food.getCarbohydrate() * 4) + (food.getProtein() * 4) + (food.getFat() * 9);
            totalCarbo += food.getCarbohydrate();
            totalProtein += food.getProtein();
            totalFat += food.getFat();
            totalKcal += foodKcal;

            // 식사별로 나누어서 저장
            switch (food.getMealtime()) {
                case BREAKFAST:
                    breakfastName = food.getName();
                    breakfastKcal += foodKcal;
                    break;
                case LUNCH:
                    lunchName = food.getName();
                    lunchKcal += foodKcal;
                    break;
                case DINNER:
                    dinnerName = food.getName();
                    dinnerKcal += foodKcal;
                    break;
            }
        }

        return MainHistoryResponseDto.builder()
                .userTotalKcal(user.getBmr())
                .userNowKcal(totalKcal)
                .userCarbo(totalCarbo)
                .userProtein(totalProtein)
                .userFat(totalFat)
                .breakfastName(breakfastName)
                .breakfastKcal(breakfastKcal)
                .lunchName(lunchName)
                .lunchKcal(lunchKcal)
                .dinnerName(dinnerName)
                .dinnerKcal(dinnerKcal)
                .build();
    }
}

 

② MainController : jwt 토큰 값으로 사용자 정보를 불러온다, 전달받은 날짜 기록 반환해주기

@RestController
@RequiredArgsConstructor
@RequestMapping("/main")
public class MainController {

    private final MainService mainService;

    @GetMapping("/history") // 식사 기록 조회
    public ApiResponse<MainHistoryResponseDto> getHistory(@RequestHeader("Authorization") String token,
                                                          @RequestParam("date") String date) {
        return ApiResponse.onSuccess(mainService.getHistory(extractUserEmail(token), date));
    }

    public String extractUserEmail(String token) {
        String jwtToken = token.substring(7);
        String userEmail = JwtUtil.getEmail(jwtToken);
        return userEmail;
    }
}

 

③ MainServiceImpl : 데이터베이스에서 사용자 - 날짜에 해당하는 식사 기록을 조회해서 Dto 에 담아 반환한다

@Service
@Transactional
@RequiredArgsConstructor
public class MainServiceImpl implements MainService {

    private final UserRepository userRepository;
    private final FoodRepository foodRepository;

    @Override
    public MainHistoryResponseDto getHistory(String userEmail, String date) {
        // 사용자 존재 여부 확인
        User user = checkUser(userEmail);

        // 날짜 변환
        LocalDate localDate = LocalDate.parse(date);

        // 사용자 - 날짜에 해당하는 음식 기록 조회
        List<Food> foodList = foodRepository.findAllByUserAndCreatedAt(user, localDate);

        return MainHistoryResponseDto.mainHistoryResponse(user, foodList);
    }

    public User checkUser(String userEmail) {
        return userRepository.findByEmail(userEmail)
                .orElseThrow(() -> new GeneralException(ErrorStatus.MEMBER_NOT_FOUND));
    }
}

 


2024.08.27 - [Spring/[P] AI 기반 사용자 맞춤형 메뉴와 맛집 추천] - [Springboot] 식사 기록 조회 설계하기

 

[Springboot] 식사 기록 조회 설계하기

📂 /main  L 기록 조회 ⬅️⬅️⬅️   L 기록 등록  L 통계 조회  🔧 디자인   🔧 필요한 데이터  L 조회하는 날짜 🔧 HTTP Method  L GET🔧 API Path  L /main/history?date=yyyy-MM-dd

alsrudalsrudalsrud.tistory.com