Skip to content

Commit a66c53b

Browse files
committed
recipe_domain include search
1 parent f527cde commit a66c53b

9 files changed

Lines changed: 149 additions & 41 deletions

File tree

src/main/java/com/webservice/algorithmchef/config/JwtAuthenticationFilter.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import org.springframework.web.filter.OncePerRequestFilter;
1414

1515
// (⭐수정) algorithmchef 프로젝트의 의존성으로 변경
16-
import com.webservice.algorithmchef.service.UserService;
16+
import com.webservice.algorithmchef.service.UserService;
1717
import com.webservice.algorithmchef.util.JwtUtil;
1818

1919
import io.jsonwebtoken.Claims;
@@ -60,13 +60,13 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
6060
claims = jwtUtil.getClaims(token);
6161
} catch (Exception e) {
6262
log.warn("유효하지 않은 JWT 토큰: {}", e.getMessage());
63-
// (참고) 여기서 401 Unauthorized를 바로 반환할 수도 있으나,
63+
// (참고) 여기서 401 Unauthorized를 바로 반환할 수도 있으나,
6464
// SecurityConfig의 exceptionHandling에서 처리하도록 위임하는 것이 일반적입니다.
6565
}
6666

6767
// 3. 토큰이 유효하고, 아직 SecurityContext에 인증 정보가 없는 경우
6868
if (claims != null && SecurityContextHolder.getContext().getAuthentication() == null) {
69-
69+
7070
// claims.getSubject()는 User 엔티티의 "userLoginId" (로그인 ID)여야 합니다.
7171
String userLoginId = claims.getSubject();
7272
String status = claims.get("status", String.class); // "status" 클레임 추출
@@ -84,11 +84,11 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
8484
return; // 필터 체인 중단
8585
}
8686
}
87-
87+
8888
// 6. (정상 사용자) 또는 (임시 사용자가 허용된 URL에 접근한 경우)
8989
// UserDetails를 DB에서 조회하여 인증 토큰 생성
9090
UserDetails userDetails = userService.loadUserByUsername(userLoginId);
91-
91+
9292
UsernamePasswordAuthenticationToken authenticationToken =
9393
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
9494
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
@@ -97,7 +97,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
9797
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
9898
log.info("SecurityContext에 인증 정보 저장 완료: {}", userLoginId);
9999
}
100-
100+
101101
// 8. 다음 필터로 체인 넘김
102102
filterChain.doFilter(request, response);
103103
}

src/main/java/com/webservice/algorithmchef/config/MailConfig.java

Lines changed: 0 additions & 16 deletions
This file was deleted.

src/main/java/com/webservice/algorithmchef/config/SecurityConfig.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
@EnableWebSecurity
1818
@RequiredArgsConstructor
1919
public class SecurityConfig {
20-
21-
private final JwtAuthenticationFilter jwtAuthenticationFilter;
20+
21+
private final JwtAuthenticationFilter jwtAuthenticationFilter;
2222

2323

2424
@Bean
@@ -34,8 +34,8 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
3434

3535
http
3636
.authorizeHttpRequests(authorize -> authorize
37-
.requestMatchers("/auth/login", "/auth/signUp",
38-
"/auth/findPassword", "/auth/findUserId").permitAll()
37+
.requestMatchers("/auth/login", "/auth/signUp",
38+
"/auth/findPassword", "/auth/findUserId").permitAll()
3939
.anyRequest().authenticated());
4040

4141
http
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.webservice.algorithmchef.controller;
2+
3+
import com.webservice.algorithmchef.model.Recipe;
4+
import com.webservice.algorithmchef.service.RecipeService;
5+
import org.springframework.http.ResponseEntity;
6+
import org.springframework.web.bind.annotation.*;
7+
8+
import java.util.Arrays;
9+
import java.util.List;
10+
11+
@RestController
12+
@RequestMapping("/api/recipes")
13+
@CrossOrigin(origins = "http://localhost:3000")
14+
public class RecipeSearchController {
15+
16+
private final RecipeService recipeService;
17+
18+
public RecipeSearchController(RecipeService recipeService) {
19+
this.recipeService = recipeService;
20+
}
21+
22+
@GetMapping("/search")
23+
public ResponseEntity<?> getRandomRecipe(@RequestParam String ingredient) {
24+
25+
Recipe recipe = recipeService.getRandomRecipeByIngredient(ingredient);
26+
27+
if (recipe == null) {
28+
return ResponseEntity.ok("검색된 레시피가 없습니다.");
29+
}
30+
31+
return ResponseEntity.ok(recipe);
32+
}
33+
34+
@GetMapping("/search-multi")
35+
public ResponseEntity<?> getRandomRecipeMultiple(@RequestParam String ingredients) {
36+
37+
List<String> ingList =
38+
Arrays.stream(ingredients.split(","))
39+
.map(String::trim)
40+
.toList();
41+
42+
Recipe recipe = recipeService.getRandomRecipeByIngredients(ingList);
43+
44+
if (recipe == null) {
45+
return ResponseEntity.ok("해당 재료들을 모두 포함한 레시피가 없습니다.");
46+
}
47+
48+
return ResponseEntity.ok(recipe);
49+
}
50+
}

src/main/java/com/webservice/algorithmchef/dto/recipe/CookRcpResponse.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ public static class Item {
8585
@JsonProperty("MANUAL19") private String manual19;
8686
@JsonProperty("MANUAL20") private String manual20;
8787

88+
@JsonProperty("RCP_NA_TIP")
89+
private String naTip;
90+
8891

8992
public String getName() {
9093
return name;
@@ -158,5 +161,8 @@ public String getInstructions() {
158161

159162
return String.join("\n", steps);
160163
}
164+
public String getTip() {
165+
return naTip;
166+
}
161167
}
162168
}

src/main/java/com/webservice/algorithmchef/model/Recipe.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public class Recipe {
3737
private String description;
3838

3939
@Lob
40-
@Column(nullable = false)
40+
@Column(nullable = false, columnDefinition = "LONGTEXT")
4141
private String instructions;
4242

4343
private String imageUrl;

src/main/java/com/webservice/algorithmchef/repository/RecipeRepository.java

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import com.webservice.algorithmchef.model.Recipe;
44
import org.springframework.data.jpa.repository.JpaRepository;
5+
import org.springframework.data.jpa.repository.Query;
6+
import org.springframework.data.repository.query.Param;
57

68
import java.util.Optional;
79
import java.util.List;
@@ -12,5 +14,23 @@ public interface RecipeRepository extends JpaRepository<Recipe, Long> {
1214

1315
boolean existsByName(String name);
1416

15-
List<Recipe> findByNeededIngredientsContaining(String ingredient);
17+
@Query("""
18+
SELECT r FROM Recipe r
19+
WHERE (:i1 = '' OR r.neededIngredients LIKE %:i1%)
20+
AND (:i2 = '' OR r.neededIngredients LIKE %:i2%)
21+
AND (:i3 = '' OR r.neededIngredients LIKE %:i3%)
22+
AND (:i4 = '' OR r.neededIngredients LIKE %:i4%)
23+
AND (:i5 = '' OR r.neededIngredients LIKE %:i5%)
24+
""")
25+
List<Recipe> findByIngredientsMulti(
26+
@Param("i1") String i1,
27+
@Param("i2") String i2,
28+
@Param("i3") String i3,
29+
@Param("i4") String i4,
30+
@Param("i5") String i5
31+
);
32+
33+
@Query("SELECT r FROM Recipe r " +
34+
"WHERE r.neededIngredients LIKE %:ingredient%")
35+
List<Recipe> findByIngredientKeyword(@Param("ingredient") String ingredient);
1636
}

src/main/java/com/webservice/algorithmchef/service/RecipeImportService.java

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -68,26 +68,21 @@ public void importAllFromFoodSafety() {
6868

6969
Recipe r = new Recipe();
7070
r.setName(name);
71-
72-
// description은 당분간 null 유지
7371
r.setDescription(null);
74-
7572
r.setInstructions(item.getInstructions());
7673
r.setImageUrl(item.getImageUrl());
77-
78-
// kcal이 null일 수 있으니까 방어 코드
7974
Double kcal = item.getKcalOrNull();
8075
r.setKcal(kcal != null ? kcal : 0.0);
8176

82-
String type = item.getType();
83-
if (type == null || type.isBlank()) {
84-
type = "기타";
77+
String originalType = item.getType();
78+
if (originalType == null || originalType.isBlank()) {
79+
originalType = "기타";
8580
}
86-
r.setType(type);
87-
88-
// ✅ 재료 전체 문자열 그대로 저장
81+
r.setTag(originalType);
82+
r.setType("식품안전나라");
83+
r.setTime(null);
84+
r.setTip(item.getTip());
8985
r.setNeededIngredients(item.getParts());
90-
9186
recipeRepository.save(r);
9287
totalSaved++;
9388
System.out.println(" -> DB save complete (current new save: " + totalSaved + ")");
@@ -98,5 +93,4 @@ public void importAllFromFoodSafety() {
9893

9994
System.out.println("[IMPORT] every import complete. A total " + totalSaved + " new saved");
10095
}
101-
10296
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.webservice.algorithmchef.service;
2+
3+
import com.webservice.algorithmchef.model.Recipe;
4+
import com.webservice.algorithmchef.repository.RecipeRepository;
5+
import org.springframework.stereotype.Service;
6+
7+
import java.util.Collections;
8+
import java.util.List;
9+
import java.util.NoSuchElementException;
10+
import java.util.Random;
11+
12+
@Service
13+
public class RecipeService {
14+
15+
private final RecipeRepository recipeRepository;
16+
private final Random random = new Random();
17+
18+
public RecipeService(RecipeRepository recipeRepository) {
19+
this.recipeRepository = recipeRepository;
20+
}
21+
22+
public Recipe getRandomRecipeByIngredient(String ingredient) {
23+
List<Recipe> list = recipeRepository.findByIngredientKeyword(ingredient);
24+
25+
if (list.isEmpty()) {
26+
return null;
27+
}
28+
29+
int idx = (int) (Math.random() * list.size());
30+
return list.get(idx);
31+
}
32+
33+
public Recipe getRandomRecipeByIngredients(List<String> ingredients) {
34+
35+
if (ingredients == null || ingredients.isEmpty()) {
36+
throw new IllegalArgumentException("재료 리스트가 필요합니다.");
37+
}
38+
39+
String i1 = ingredients.size() > 0 ? ingredients.get(0) : "";
40+
String i2 = ingredients.size() > 1 ? ingredients.get(1) : "";
41+
String i3 = ingredients.size() > 2 ? ingredients.get(2) : "";
42+
String i4 = ingredients.size() > 3 ? ingredients.get(3) : "";
43+
String i5 = ingredients.size() > 4 ? ingredients.get(4) : "";
44+
45+
List<Recipe> list =
46+
recipeRepository.findByIngredientsMulti(i1, i2, i3, i4, i5);
47+
48+
if (list.isEmpty()) {
49+
return null;
50+
}
51+
52+
return list.get(random.nextInt(list.size()));
53+
}
54+
}

0 commit comments

Comments
 (0)