Skip to content

Commit 18701f3

Browse files
authored
Merge pull request #10 from AlgorithmChef/feature/recipe_domain
Feature/recipe domain merge
2 parents a2851e8 + 838cc89 commit 18701f3

17 files changed

Lines changed: 633 additions & 135 deletions
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package com.webservice.algorithmchef.client;
2+
3+
import com.webservice.algorithmchef.dto.recipe.CookRcpResponse;
4+
import org.springframework.beans.factory.annotation.Value;
5+
import org.springframework.stereotype.Service;
6+
import org.springframework.web.client.RestTemplate;
7+
8+
import java.util.ArrayList;
9+
import java.util.List;
10+
import java.util.Optional;
11+
12+
@Service
13+
public class FoodSafetyApiClient {
14+
15+
private final RestTemplate restTemplate;
16+
17+
public FoodSafetyApiClient(RestTemplate restTemplate) {
18+
this.restTemplate = restTemplate;
19+
}
20+
21+
@Value("${foodsafety.cookrcp.base-url}")
22+
private String baseUrl;
23+
24+
@Value("${foodsafety.cookrcp.service-key}")
25+
private String serviceKey;
26+
27+
@Value("${foodsafety.cookrcp.svc-no}")
28+
private String svcNo;
29+
30+
public int getTotalCount() {
31+
String url = String.format("%s/%s/%s/json/1/1",
32+
baseUrl, serviceKey, svcNo);
33+
34+
CookRcpResponse res = restTemplate.getForObject(url, CookRcpResponse.class);
35+
36+
if (res == null || res.getCOOKRCP01() == null) return 0;
37+
38+
try {
39+
return Integer.parseInt(res.getCOOKRCP01().getTotalCount());
40+
} catch (Exception e) {
41+
return 0;
42+
}
43+
}
44+
45+
public List<CookRcpResponse.Item> fetchRange(int start, int end) {
46+
String url = String.format("%s/%s/%s/json/%d/%d",
47+
baseUrl, serviceKey, svcNo, start, end);
48+
49+
CookRcpResponse res = restTemplate.getForObject(url, CookRcpResponse.class);
50+
51+
return Optional.ofNullable(res)
52+
.map(CookRcpResponse::getCOOKRCP01)
53+
.map(CookRcpResponse.Body::getRow)
54+
.orElse(List.of());
55+
}
56+
57+
public List<CookRcpResponse.Item> fetchAll() {
58+
int total = getTotalCount();
59+
if (total <= 0) return List.of();
60+
61+
int pageSize = 200;
62+
List<CookRcpResponse.Item> all = new ArrayList<>(total);
63+
64+
for (int start = 1; start <= total; start += pageSize) {
65+
int end = Math.min(start + pageSize - 1, total);
66+
all.addAll(fetchRange(start, end));
67+
}
68+
69+
return all;
70+
}
71+
}

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
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.webservice.algorithmchef.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.web.client.RestTemplate;
6+
7+
@Configuration
8+
public class RestTemplateConfig {
9+
10+
@Bean
11+
public RestTemplate restTemplate() {
12+
return new RestTemplate();
13+
}
14+
}

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

src/main/java/com/webservice/algorithmchef/controller/RecipeReviewController.java

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,19 @@
1717
@RestController
1818
@RequiredArgsConstructor
1919
public class RecipeReviewController {
20-
21-
private final RecipeReviewService rService;
22-
23-
@PostMapping("/recipe/review")
24-
public ResponseEntity<?> makeReview(@RequestBody RecipeReviewRequest request,
25-
@AuthenticationPrincipal UserDetails userDetails){
26-
try {
27-
String userId = userDetails.getUsername();
28-
RecipeReviewResponse response = rService.makeReview(request, userId);
29-
return ResponseEntity.status(HttpStatus.CREATED).body(response);
30-
}catch (IllegalArgumentException e) {
31-
return ResponseEntity.badRequest().body(e.getMessage());
32-
}
33-
}
20+
21+
private final RecipeReviewService rService;
22+
23+
@PostMapping("/recipe/review")
24+
public ResponseEntity<?> makeReview(@RequestBody RecipeReviewRequest request,
25+
@AuthenticationPrincipal UserDetails userDetails){
26+
try {
27+
String userId = userDetails.getUsername();
28+
RecipeReviewResponse response = rService.makeReview(request, userId);
29+
return ResponseEntity.status(HttpStatus.CREATED).body(response);
30+
}catch (IllegalArgumentException e) {
31+
return ResponseEntity.badRequest().body(e.getMessage());
32+
}
33+
}
3434

3535
}
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+
}

0 commit comments

Comments
 (0)