Skip to content

Commit

Permalink
Merge pull request #143 from CAUSOLDOUTMEN/feature/142-refactor
Browse files Browse the repository at this point in the history
Refactor: �즐찾음식 관계단절 이슈 등 리팩토링 (#142)
  • Loading branch information
synoti21 authored Jan 16, 2024
2 parents 9dbd5e4 + 0a43a0d commit 94530d3
Show file tree
Hide file tree
Showing 6 changed files with 16 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package com.diareat.diareat.food.repository;

import com.diareat.diareat.food.domain.Food;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDate;
import java.util.List;

public interface FoodRepository extends JpaRepository<Food, Long> {
boolean existsByIdAndUserId(Long id, Long userId); // 유저가 먹은 음식인지 확인
boolean existsByName(String name);
List<Food> findAllByUserIdAndDateOrderByAddedTimeAsc(Long userId, LocalDate date); //유저가 특정 날짜에 먹은 음식 반환
List<Food> findAllByUserIdAndDateBetweenOrderByAddedTimeAsc(Long userId, LocalDate startDate, LocalDate endDate); // 유저가 특정 기간 내에 먹은 음식 반환

// 특정 즐겨찾기 음식으로부터 태어난 음식 데이터의, 즐겨찾기 음식과의 연관관계를 해제
@Query(value = "UPDATE Food f set f.favoriteFood = null where f.favoriteFood.id = :id")
void updateFoodRelationShipWithFavoriteFood(@Param("id")Long favoriteFoodId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,8 @@ public void updateFavoriteFood(UpdateFavoriteFoodDto updateFavoriteFoodDto) {
@Transactional
public void deleteFavoriteFood(Long favoriteFoodId, Long userId) {
validateFavoriteFood(favoriteFoodId, userId);
FavoriteFood favoriteFood = getFavoriteFoodById(favoriteFoodId);
favoriteFood.getFoods().forEach(food -> food.setFavoriteFood(null)); // 즐겨찾기 음식으로부터 태어난 음식들의 즐겨찾기 정보를 null로 초기화
favoriteFoodRepository.deleteById(favoriteFoodId);
foodRepository.updateFoodRelationShipWithFavoriteFood(favoriteFoodId);
log.info("즐겨찾기 음식 해제 완료: " + favoriteFoodId);
}

Expand Down
19 changes: 0 additions & 19 deletions src/main/java/com/diareat/diareat/user/domain/BaseNutrition.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,4 @@ public static BaseNutrition createNutrition(int kcal, int carbohydrate, int prot
baseNutrition.fat = fat;
return baseNutrition;
}

// 생성 메서드 by 개인정보 (성별, 나이, 키, 몸무게로 기준영양소 자동 계산 기능)
public static BaseNutrition calculateNutrition(int gender, int age, int height, int weight) {
BaseNutrition baseNutrition = new BaseNutrition();

// 임의의 식으로 기초대사량 계산하였으며, 추후 식약처 및 관련 기관에서 제공하는 공식으로 변경할 예정
baseNutrition.kcal = (int) (66.47 + (13.75 * weight) + (5 * height) - (6.76 * age)); // 기초대사량 계산식
baseNutrition.carbohydrate = (int) (baseNutrition.kcal * 0.65 / 4); // 탄수화물 65%
baseNutrition.protein = (int) (baseNutrition.kcal * 0.1 / 4); // 단백질 10%
baseNutrition.fat = (int) (baseNutrition.kcal * 0.25 / 9);

if(gender == 1) { // 여성일 경우
baseNutrition.kcal -= 161;
baseNutrition.carbohydrate -= 40;
baseNutrition.protein -= 5;
baseNutrition.fat -= 10;
}
return baseNutrition;
}
}
6 changes: 5 additions & 1 deletion src/main/java/com/diareat/diareat/user/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import reactor.util.annotation.Nullable;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
Expand Down Expand Up @@ -44,6 +45,8 @@ public class User implements UserDetails {

private int type; // 성별과 연령에 따른 유저 타입 (1~12)

private LocalDateTime createdTime; // 회원가입 시간

private BaseNutrition baseNutrition; // 기준영양소

@OneToMany(mappedBy = "user", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) // 유저가 탈퇴하면 촬영한 음식도 삭제
Expand All @@ -54,7 +57,7 @@ public class User implements UserDetails {

// Jwt 전용 설정 (UserDetails 인터페이스 구현)

@ElementCollection(fetch = FetchType.EAGER) //roles 컬렉션
@ElementCollection(fetch = FetchType.LAZY) //roles 컬렉션
private List<String> roles = new ArrayList<>();

@Override //사용자의 권한 목록 리턴
Expand Down Expand Up @@ -108,6 +111,7 @@ public static User createUser(String name, String image, String keyCode, int hei
user.age = age;
user.baseNutrition = baseNutrition;
user.type = UserTypeUtil.decideUserType(gender, age);
user.createdTime = LocalDateTime.now();
return user;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
package com.diareat.diareat.user.repository;

import com.diareat.diareat.user.domain.User;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {

@EntityGraph(attributePaths = {"roles"})
List<User> findAllByNameContaining(String name); // 회원이 팔로우를 위해 검색한 유저 목록 조회

boolean existsByName(String name); // 회원가입 시 닉네임 중복 확인
boolean existsByKeyCode(String keyCode); // 카카오 회원가입 시 중복 확인
Optional<User> findByKeyCode(String keyCode); // 카카오 회원가입 시 중복 확인
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,6 @@ void testDeleteFavoriteFood() throws NoSuchFieldException, IllegalAccessExceptio

given(favoriteFoodRepository.existsById(favoriteFood.getId())).willReturn(true);
given(favoriteFoodRepository.existsByIdAndUserId(favoriteFood.getId(), 1L)).willReturn(true);
given(favoriteFoodRepository.findById(favoriteFood.getId())).willReturn(Optional.of(favoriteFood));

//when
foodService.deleteFavoriteFood(favoriteFood.getId(), 1L);
Expand Down

0 comments on commit 94530d3

Please sign in to comment.