Skip to content

Conversation

@ehddms0320
Copy link

@ehddms0320 ehddms0320 commented Jun 1, 2025

변경사항 요약

  • 모집글 상세조회 시 유저 정보를 user-service에서 가져오도록 UserClient 구현
  • RecruitmentDetailDto에 UserDto 생성자 수정
  • RecruitmentController에서 UserClient 사용하도록 수정

참고 사항

  • user-service 서버가 실행 중이어야 정상 응답됩니다
  • 예외 처리 및 에러코드는 기존 CustomException 사용

Summary by CodeRabbit

  • 신규 기능

    • 외부 사용자 서비스와 연동하여 모집글 작성자 및 참가자 정보를 상세하게 조회할 수 있습니다.
    • 모집글 및 관련 응답에 새로운 DTO 구조가 도입되어, 보다 구조화된 데이터가 제공됩니다.
    • 모집글 생성 시 작성자가 자동으로 참가자로 등록됩니다.
  • 버그 수정

    • 예외 발생 시 일관된 API 응답 포맷으로 에러 메시지와 상태 코드가 반환됩니다.
    • Swagger 관련 요청 시 예외 처리 동작이 개선되었습니다.
  • 개선 사항

    • 모집글 관련 모든 API 응답이 표준화된 ApiResponse 형태로 제공됩니다.
    • 모집글 상태 변경 시 유효성 검사가 강화되어, 잘못된 상태 변경 시 상세 오류 메시지가 반환됩니다.
    • 메뉴 정보 입력 시 최소 1개 이상 필수로 선택해야 하며, 미입력 시 검증 오류가 발생합니다.
    • 엔티티 필드에 대한 DB 제약조건 및 명확한 주석이 추가되었습니다.
  • 설정

    • 외부 사용자 서비스 연동을 위한 URL 설정이 추가되었습니다.

@ehddms0320 ehddms0320 had a problem deploying to recruitment-service June 1, 2025 09:28 — with GitHub Actions Failure
@coderabbitai
Copy link

coderabbitai bot commented Jun 1, 2025

Walkthrough

이번 변경에서는 모집 서비스의 API 응답을 일관된 구조로 개선하고, 예외 처리와 외부 사용자 서비스 연동을 강화했습니다. 신규 DTO 및 설정 클래스가 도입되었으며, 엔티티에 명확한 JPA 설정과 유효성 검증이 추가되었습니다. 사용자 정보는 외부 서비스에서 조회하도록 변경되었습니다.

Changes

파일/경로 그룹 변경 요약
.../config/RestTemplateConfig.java
.../service/UserClient.java
.../resources/application.properties
RestTemplate 설정 및 외부 사용자 서비스 연동, 사용자 서비스 URL 프로퍼티 추가
.../controller/RecruitmentController.java 모든 컨트롤러 응답을 ApiResponse로 래핑, 예외 처리 개선, 외부 사용자 서비스 연동, 신규 DTO 적용
.../dto/RecruitmentDetailDto.java
.../dto/RecruitmentResponseDto.java
엔티티 참조 대신 중첩 DTO 도입, 생성자 및 필드 개선, orderIds 필드 추가, 신규 RecruitmentResponseDto 클래스 추가
.../dto/RecruitmentRequestDto.java menus 필드에 NotNull 및 Size 유효성 검증 추가
.../entity/Recruitment.java
.../entity/RecruitmentParticipant.java
.../entity/User.java
JPA 연관관계 및 컬럼 제약 명확화, 지연 로딩 설정, PrePersist 콜백 추가, 테이블명/컬럼 제약/JsonIgnoreProperties 추가
.../exception/GlobalExceptionHandler.java IllegalArgumentException 핸들러 추가, Swagger 경로 예외는 처리하지 않도록 변경
.../service/OrderClient.java 주문 생성시 응답 검증 및 예외 처리 강화
.../service/RecruitmentService.java 모집 생성시 ID 반환, 생성자 자동 참여자 등록 로직 추가, 주석 보완

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RecruitmentController
    participant RecruitmentService
    participant UserClient
    participant OrderClient
    participant UserService

    Client->>RecruitmentController: 모집 상세 조회 요청
    RecruitmentController->>RecruitmentService: 모집 상세 조회 호출
    RecruitmentService->>UserClient: 작성자 정보 조회
    UserClient->>UserService: GET /api/v1/users/{userId}
    UserService-->>UserClient: UserDto 반환
    UserClient-->>RecruitmentService: UserDto 반환
    RecruitmentService->>UserClient: 참여자 정보 반복 조회
    UserClient->>UserService: GET /api/v1/users/{participantId}
    UserService-->>UserClient: UserDto 반환
    UserClient-->>RecruitmentService: UserDto 반환
    RecruitmentService-->>RecruitmentController: RecruitmentDetailDto 반환
    RecruitmentController-->>Client: ApiResponse<RecruitmentDetailDto> 반환
Loading

Poem

🐇
새로운 DTO와 응답의 통일,
외부 서비스와의 연결이 빛나네.
예외 처리도 탄탄해진 오늘,
토끼는 깡충, 코드를 응원해!
모집의 길이 더 안전해졌으니,
모두 함께 주문하러 가볼까?
🥕

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🔭 Outside diff range comments (1)
recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java (1)

115-134: 🛠️ Refactor suggestion

비즈니스 로직을 서비스 레이어로 이동하는 것을 고려해보세요.

현재 구현의 개선점:

  1. 매직 넘버 3이 하드코딩되어 있습니다.
  2. 상태 변경 로직이 컨트롤러에 직접 구현되어 있습니다.

다음과 같이 상수를 정의하고 로직을 서비스로 이동하는 것을 제안합니다:

+    private static final int MIN_PARTICIPANT_COUNT = 3;
+
     @PatchMapping("/{recruitmentId}/status")
     public ResponseEntity<ApiResponse<String>> updateRecruitmentStatus(@PathVariable Long recruitmentId) {
-        Recruitment recruitment = recruitmentRepository.findById(recruitmentId)
-                .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND));
-
-        LocalDateTime now = LocalDateTime.now();
-        long participantCount = participantRepository.countByRecruitmentId(recruitmentId);
-
-        if (now.isAfter(recruitment.getDeadlineTime())) {
-            if (participantCount >= 3) {
-                recruitment.setStatus("CONFIRMED");
-            } else {
-                recruitment.setStatus("FAILED");
-            }
-            recruitmentRepository.save(recruitment);
-            return ResponseEntity.ok(ApiResponse.ok(null, "상태가 " + recruitment.getStatus() + "로 변경되었습니다."));
-        } else {
-            return ResponseEntity.ok(ApiResponse.ok(null, "아직 마감 시간이 지나지 않았습니다."));
-        }
+        String result = recruitmentService.updateRecruitmentStatus(recruitmentId);
+        return ResponseEntity.ok(ApiResponse.ok(null, result));
     }
🧹 Nitpick comments (9)
recruitment-service/src/main/resources/application.properties (1)

11-11: 환경별 설정을 고려해주세요.

하드코딩된 localhost URL은 개발, 테스트, 프로덕션 환경에서 서로 다른 값이 필요할 수 있습니다. 환경 변수나 프로파일별 설정 파일 사용을 고려해보세요.

-user.server.url=http://localhost:8080
+user.server.url=${USER_SERVICE_URL:http://localhost:8080}

또는 환경별 설정 파일(application-dev.properties, application-prod.properties)을 생성하는 것을 권장합니다.

recruitment-service/src/main/java/com/example/recruitment/config/RestTemplateConfig.java (1)

9-12: 프로덕션을 위한 추가 설정을 고려해보세요.

기본 RestTemplate 설정은 올바르지만, 프로덕션 환경에서는 타임아웃과 에러 핸들링 설정을 추가하는 것이 좋습니다.

 @Bean
 public RestTemplate restTemplate() {
-    return new RestTemplate();
+    RestTemplate restTemplate = new RestTemplate();
+    
+    // 타임아웃 설정
+    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
+    factory.setConnectTimeout(5000);
+    factory.setReadTimeout(10000);
+    restTemplate.setRequestFactory(factory);
+    
+    return restTemplate;
 }
recruitment-service/src/main/java/com/example/recruitment/exception/GlobalExceptionHandler.java (1)

39-45: 일관성을 위해 ErrorCode enum 사용을 고려해보세요.

현재 하드코딩된 에러 코드(4000) 대신 ErrorCode enum을 사용하는 것이 좋겠습니다. 다른 예외 핸들러들과 일관성을 유지할 수 있습니다.

 @ExceptionHandler(IllegalArgumentException.class)
 public ResponseEntity<ApiResponse<Object>> handleIllegalArgument(IllegalArgumentException e) {
     return ResponseEntity
             .badRequest()
-            .body(ApiResponse.fail(4000, e.getMessage(), HttpStatus.BAD_REQUEST));
+            .body(ApiResponse.fail(ErrorCode.INVALID_INPUT.getCode(), e.getMessage(), HttpStatus.BAD_REQUEST));
 }
recruitment-service/src/main/java/com/example/recruitment/service/UserClient.java (1)

21-21: URL 생성 방법을 개선해보세요.

문자열 연결 대신 UriComponentsBuilder를 사용하면 더 안전하고 읽기 쉬운 코드가 됩니다.

+import org.springframework.web.util.UriComponentsBuilder;

 public UserDto getUserById(Long userId) {
-    String url = userServerUrl + "/api/v1/users/" + userId;
+    String url = UriComponentsBuilder.fromHttpUrl(userServerUrl)
+            .path("/api/v1/users/{userId}")
+            .buildAndExpand(userId)
+            .toUriString();
recruitment-service/src/main/java/com/example/recruitment/entity/Recruitment.java (1)

17-18: GeneratedValue 전략을 명시하는 것을 권장합니다.

현재 기본 전략을 사용하고 있지만, 명시적으로 전략을 지정하는 것이 좋습니다.

다음과 같이 수정하는 것을 권장합니다:

-    @GeneratedValue
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
recruitment-service/src/main/java/com/example/recruitment/service/OrderClient.java (1)

48-50: 로깅 프레임워크 사용을 권장합니다.

System.err.println 대신 SLF4J 등의 로깅 프레임워크를 사용하는 것이 좋습니다.

다음과 같이 수정하는 것을 권장합니다:

+    private static final Logger log = LoggerFactory.getLogger(OrderClient.class);
+    
-            System.err.println("Order 서버 호출 중 예외 발생: " + e.getMessage());
+            log.error("Order 서버 호출 중 예외 발생: {}", e.getMessage(), e);
recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java (3)

172-195: 작성자 검증 로직이 잘 구현되었습니다.

보안을 위한 작성자 검증이 적절히 구현되었습니다.

한 가지 작은 개선사항으로, 에러 메시지를 더 구체적으로 만들 수 있습니다:

-            Store store = storeRepository.findById(dto.getStoreId())
-                    .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND));
+            Store store = storeRepository.findById(dto.getStoreId())
+                    .orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND, "가게를 찾을 수 없습니다."));

37-37: 주석 언어를 통일하는 것이 좋습니다.

프로젝트 전체에서 주석 언어를 한국어 또는 영어로 통일하는 것을 권장합니다.

-    private final UserClient userClient; // 유저 서비스 연동용 Feign Client
+    private final UserClient userClient; // 유저 서비스 연동용 클라이언트

또는 영어로:

-    private final UserClient userClient; // 유저 서비스 연동용 Feign Client
+    private final UserClient userClient; // Client for user service integration

1-197: 전체적인 아키텍처 개선 제안

user-service와의 통합이 잘 구현되었습니다. 추가로 고려할 사항들:

  1. 서킷 브레이커 패턴: user-service가 다운되었을 때를 대비한 폴백 메커니즘
  2. 캐싱: 자주 조회되는 사용자 정보는 캐싱을 고려해보세요
  3. 비동기 처리: 대량의 사용자 정보 조회 시 비동기 처리를 고려해보세요
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f478d9b and 8899246.

📒 Files selected for processing (13)
  • recruitment-service/src/main/java/com/example/recruitment/config/RestTemplateConfig.java (1 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java (3 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentDetailDto.java (1 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentRequestDto.java (1 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentResponseDto.java (1 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/entity/Recruitment.java (1 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/entity/RecruitmentParticipant.java (2 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/entity/User.java (1 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/exception/GlobalExceptionHandler.java (3 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/service/OrderClient.java (1 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/service/RecruitmentService.java (3 hunks)
  • recruitment-service/src/main/java/com/example/recruitment/service/UserClient.java (1 hunks)
  • recruitment-service/src/main/resources/application.properties (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
recruitment-service/src/main/java/com/example/recruitment/entity/RecruitmentParticipant.java (2)
recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentDetailDto.java (3)
  • Getter (11-72)
  • Getter (43-55)
  • Getter (57-71)
recruitment-service/src/main/java/com/example/recruitment/dto/order/OrderResponseDto.java (1)
  • Getter (6-10)
recruitment-service/src/main/java/com/example/recruitment/entity/Recruitment.java (5)
recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentResponseDto.java (3)
  • Getter (11-63)
  • Getter (34-46)
  • Getter (48-62)
recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentDetailDto.java (3)
  • Getter (11-72)
  • Getter (43-55)
  • Getter (57-71)
recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentRequestDto.java (1)
  • Getter (13-48)
recruitment-service/src/main/java/com/example/recruitment/dto/order/OrderRequestDto.java (3)
  • Getter (8-32)
  • Getter (17-24)
  • Getter (26-31)
recruitment-service/src/main/java/com/example/recruitment/dto/order/OrderResponseDto.java (1)
  • Getter (6-10)
recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentResponseDto.java (2)
recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentDetailDto.java (3)
  • Getter (11-72)
  • Getter (43-55)
  • Getter (57-71)
recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentRequestDto.java (1)
  • Getter (13-48)
🪛 GitHub Actions: CI/CD for Spring Boot + MySQL with Docker Compose
recruitment-service/src/main/java/com/example/recruitment/service/OrderClient.java

[warning] 1-1: Uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details.

🔇 Additional comments (28)
recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentRequestDto.java (1)

36-37: 입력 검증 강화가 잘 구현되었습니다.

메뉴 정보에 대한 @NotNull@Size(min = 1) 어노테이션 추가로 데이터 무결성이 향상되었습니다. 이는 최소 하나 이상의 메뉴 선택을 보장하는 좋은 방법입니다.

recruitment-service/src/main/java/com/example/recruitment/service/RecruitmentService.java (4)

25-25: OrderClient 의존성 추가가 적절합니다.

외부 주문 서비스와의 연동을 위한 OrderClient 의존성 추가가 올바르게 구현되었습니다.


36-36: 반환 타입 변경이 적절합니다.

createRecruitment 메서드가 생성된 모집글의 ID를 반환하도록 변경된 것은 좋은 개선사항입니다. API 응답에서 생성된 리소스의 식별자를 제공할 수 있게 됩니다.


54-60: 트랜잭션 경계 내 외부 서비스 호출을 검토해주세요.

@transactional 메서드 내에서 외부 서비스(OrderClient)를 호출하고 있습니다. 외부 서비스 호출이 실패할 경우 전체 트랜잭션이 롤백될 수 있습니다.

외부 서비스 호출과 트랜잭션 경계를 분리하는 것을 고려해보세요:

 @Transactional
 public Long createRecruitment(RecruitmentRequestDto dto) {
     // ... 모집글 저장 로직
-    
-    // 주문 서버에 주문 생성 요청
-    OrderRequestDto orderDto = dto.toOrderRequestDto();
-    orderDto.setGroupId(recruitment.getId());
-    Long orderId = orderClient.createOrder(orderDto);
-    
-    // 모집글에 orderId 저장
-    recruitment.setOrderId(orderId);
-    recruitmentRepository.save(recruitment);
-    
-    // 모집자도 자동으로 참여자로 등록
-    RecruitmentParticipant participant = new RecruitmentParticipant();
-    participant.setRecruitment(recruitment);
-    participant.setUser(user);
-    participant.setOrderId(orderId);
-    participantRepository.save(participant);
     
     return recruitment.getId();
 }
+
+// 별도 메서드로 분리하여 트랜잭션 전파 설정
+@Transactional(propagation = Propagation.REQUIRES_NEW)
+public void processOrderAndParticipant(Long recruitmentId, RecruitmentRequestDto dto) {
+    // 외부 서비스 호출 및 참여자 등록 로직
+}

62-68: 모집자 자동 참여 기능이 잘 구현되었습니다.

모집글 생성자가 자동으로 참여자로 등록되는 기능이 추가되어 사용자 경험이 개선되었습니다. 로직이 명확하고 올바르게 구현되었습니다.

recruitment-service/src/main/java/com/example/recruitment/exception/GlobalExceptionHandler.java (1)

52-55: Swagger 요청 필터링이 잘 구현되었습니다.

Swagger 관련 요청을 필터링하여 원래 Spring 동작을 유지하는 것은 좋은 접근법입니다. 문서 생성에 간섭하지 않도록 방지합니다.

recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentResponseDto.java (1)

24-32: PR 목표와 일치하지 않는 User 엔티티 사용

PR의 주요 목표는 사용자 정보를 user-service에서 조회하는 것인데, 현재 코드는 여전히 User 엔티티를 직접 사용하고 있습니다. UserClient를 통해 외부 서비스에서 사용자 정보를 가져와야 합니다.

생성자를 다음과 같이 수정해보세요:

-public RecruitmentResponseDto(Recruitment recruitment) {
+public RecruitmentResponseDto(Recruitment recruitment, UserDto userDto) {
     this.id = recruitment.getId();
     this.title = recruitment.getTitle();
     this.description = recruitment.getDescription();
     this.status = recruitment.getStatus();
     this.deadlineTime = recruitment.getDeadlineTime();
-    this.user = new UserDto(recruitment.getUser());
+    this.user = userDto;
     this.store = new StoreDto(recruitment.getStore());
 }

Likely an incorrect or invalid review comment.

recruitment-service/src/main/java/com/example/recruitment/entity/RecruitmentParticipant.java (3)

20-22: Lazy 페칭 설정이 잘 적용되었습니다.

연관관계에 FetchType.LAZY 설정은 N+1 문제를 방지하고 성능을 향상시키는 좋은 방법입니다.


38-43: 생명주기 콜백이 잘 구현되었습니다.

@PrePersist를 사용하여 joinedAt 필드를 자동으로 설정하는 것은 좋은 접근법입니다. null 체크를 통해 수동 설정을 허용하면서도 자동화를 제공합니다.


19-35: 필드 설명 주석이 코드 가독성을 향상시켰습니다.

각 필드의 역할과 null 허용 여부를 명시한 주석이 코드 이해에 도움이 됩니다.

recruitment-service/src/main/java/com/example/recruitment/entity/Recruitment.java (6)

11-12: Lombok 어노테이션 추가가 적절합니다.

@Getter@Setter 어노테이션이 추가되어 보일러플레이트 코드를 줄이고 코드 가독성을 향상시킵니다.


21-24: JPA 연관관계 설정이 적절합니다.

작성자 필드에 대한 lazy 로딩과 nullable=false 제약 조건이 올바르게 설정되었습니다. 주석도 명확하여 코드 이해에 도움이 됩니다.


26-29: Store 연관관계 설정이 적절합니다.

가게 필드에 대한 lazy 로딩과 nullable=false 제약 조건이 올바르게 설정되었습니다.


31-33: 참여자 목록 초기화가 좋습니다.

컬렉션을 빈 ArrayList로 초기화하여 null 참조 오류를 방지하고, cascade와 orphanRemoval 설정도 적절합니다.


35-50: 필드 제약 조건이 적절하게 설정되었습니다.

모든 필수 필드에 nullable=false 제약이 추가되어 데이터 무결성이 향상되었습니다. 주석도 명확합니다.


55-61: 주문 ID 목록 관리가 적절합니다.

ElementCollection을 사용하여 주문 ID 목록을 관리하고, 빈 리스트로 초기화하여 null 참조를 방지했습니다. addOrderId 메소드도 간단하고 명확합니다.

recruitment-service/src/main/java/com/example/recruitment/entity/User.java (5)

3-3: JSON 직렬화 개선을 위한 import가 적절합니다.

JsonIgnoreProperties import가 추가되어 Hibernate 프록시 객체 직렬화 문제를 해결할 수 있습니다.


8-8: SQL 예약어 충돌 방지가 훌륭합니다.

백틱을 사용하여 'user' 테이블명의 SQL 예약어 충돌을 방지한 것이 적절합니다.


9-13: Lombok 어노테이션과 JSON 설정이 적절합니다.

@Getter, @Setter 추가로 코드 간소화가 이루어졌고, @JsonIgnoreProperties로 Hibernate lazy loading 관련 직렬화 오류를 방지했습니다.


16-18: ID 생성 전략이 명시적으로 설정되었습니다.

GenerationType.IDENTITY를 명시적으로 지정하여 데이터베이스 자동 증가 컬럼을 사용하도록 했습니다.


20-24: 데이터베이스 제약 조건이 적절히 설정되었습니다.

name과 email 필드에 nullable=false 제약이 추가되었고, email 필드에는 unique 제약도 추가되어 데이터 무결성이 향상되었습니다.

recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentDetailDto.java (6)

3-4: import 구문이 적절합니다.

Recruitment와 Store 엔티티만 import하고 User 엔티티 의존성을 제거한 것이 외부 사용자 서비스 통합에 적합합니다.


11-12: Lombok 어노테이션 추가가 적절합니다.

@Getter@Setter 어노테이션으로 보일러플레이트 코드를 줄였습니다.


21-24: DTO 패턴으로의 전환이 훌륭합니다.

직접적인 엔티티 참조에서 UserDto, StoreDto 사용으로 변경하여 계층 간 분리와 외부 서비스 통합이 개선되었습니다.


26-41: 생성자 설계가 외부 서비스 통합에 적합합니다.

외부 사용자 서비스에서 가져온 UserDto를 매개변수로 받는 생성자 설계가 PR 목표와 일치합니다. 주석도 명확하여 의도를 잘 표현했습니다.


43-55: UserDto 중첩 클래스가 잘 설계되었습니다.

외부 사용자 서비스 응답을 위한 간단하고 명확한 DTO 구조입니다. 생성자 매개변수가 적절합니다.


57-71: StoreDto 중첩 클래스가 적절합니다.

Store 엔티티에서 필요한 정보만 추출하는 명확한 구조입니다. 엔티티를 매개변수로 받는 생성자가 적절합니다.

recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java (1)

39-45: 좋은 변경사항입니다!

적절한 HTTP 상태 코드(201 CREATED)와 구조화된 응답을 사용하여 RESTful API 원칙을 잘 따르고 있습니다.

Comment on lines 37 to 40
User user = userRepository.findById(dto.getUserId())
.orElseThrow(() -> new RuntimeException("사용자 없음"));
Store store = storeRepository.findById(dto.getStoreId())
.orElseThrow(() -> new RuntimeException("가게 없음"));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

예외 처리를 개선해주세요.

현재 RuntimeException을 사용하고 있지만, 비즈니스 로직에 맞는 구체적인 예외를 사용하는 것이 좋습니다.

-        User user = userRepository.findById(dto.getUserId())
-                .orElseThrow(() -> new RuntimeException("사용자 없음"));
-        Store store = storeRepository.findById(dto.getStoreId())
-                .orElseThrow(() -> new RuntimeException("가게 없음"));
+        User user = userRepository.findById(dto.getUserId())
+                .orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));
+        Store store = storeRepository.findById(dto.getStoreId())
+                .orElseThrow(() -> new CustomException(ErrorCode.STORE_NOT_FOUND));

PR 목표에서 언급된 기존 CustomException 프레임워크를 활용하는 것이 일관성 있는 접근방법입니다.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
User user = userRepository.findById(dto.getUserId())
.orElseThrow(() -> new RuntimeException("사용자 없음"));
Store store = storeRepository.findById(dto.getStoreId())
.orElseThrow(() -> new RuntimeException("가게 없음"));
User user = userRepository.findById(dto.getUserId())
.orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));
Store store = storeRepository.findById(dto.getStoreId())
.orElseThrow(() -> new CustomException(ErrorCode.STORE_NOT_FOUND));
🤖 Prompt for AI Agents
In
recruitment-service/src/main/java/com/example/recruitment/service/RecruitmentService.java
around lines 37 to 40, replace the generic RuntimeException with specific custom
exceptions defined in the existing CustomException framework for "사용자 없음" and
"가게 없음" cases. This involves throwing the appropriate custom exceptions that
reflect the business logic more clearly and maintain consistency with the
project's exception handling approach.

Comment on lines +20 to +24
public UserDto getUserById(Long userId) {
String url = userServerUrl + "/api/v1/users/" + userId;
ResponseEntity<UserDto> response = restTemplate.getForEntity(url, UserDto.class);
return response.getBody();
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

외부 서비스 호출 시 에러 처리가 필요합니다.

현재 구현에서는 다음과 같은 문제들이 발생할 수 있습니다:

  • 네트워크 오류 시 예외 처리 부재
  • 404, 500 등 HTTP 에러 응답 처리 부재
  • response.getBody()가 null일 경우 처리 부재

다음과 같이 개선해보세요:

 public UserDto getUserById(Long userId) {
     String url = userServerUrl + "/api/v1/users/" + userId;
-    ResponseEntity<UserDto> response = restTemplate.getForEntity(url, UserDto.class);
-    return response.getBody();
+    try {
+        ResponseEntity<UserDto> response = restTemplate.getForEntity(url, UserDto.class);
+        if (response.getBody() == null) {
+            throw new CustomException(ErrorCode.USER_NOT_FOUND);
+        }
+        return response.getBody();
+    } catch (HttpClientErrorException.NotFound e) {
+        throw new CustomException(ErrorCode.USER_NOT_FOUND);
+    } catch (Exception e) {
+        throw new CustomException(ErrorCode.USER_SERVICE_ERROR);
+    }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public UserDto getUserById(Long userId) {
String url = userServerUrl + "/api/v1/users/" + userId;
ResponseEntity<UserDto> response = restTemplate.getForEntity(url, UserDto.class);
return response.getBody();
}
public UserDto getUserById(Long userId) {
String url = userServerUrl + "/api/v1/users/" + userId;
try {
ResponseEntity<UserDto> response = restTemplate.getForEntity(url, UserDto.class);
if (response.getBody() == null) {
throw new CustomException(ErrorCode.USER_NOT_FOUND);
}
return response.getBody();
} catch (HttpClientErrorException.NotFound e) {
throw new CustomException(ErrorCode.USER_NOT_FOUND);
} catch (Exception e) {
throw new CustomException(ErrorCode.USER_SERVICE_ERROR);
}
}
🤖 Prompt for AI Agents
In
recruitment-service/src/main/java/com/example/recruitment/service/UserClient.java
around lines 20 to 24, the getUserById method lacks error handling for external
service calls. To fix this, wrap the restTemplate.getForEntity call in a
try-catch block to handle network exceptions, check the HTTP status code in the
ResponseEntity to handle 404, 500, and other error responses appropriately, and
add a null check for response.getBody() to avoid returning null or causing
NullPointerExceptions. Implement proper fallback or exception throwing based on
these checks.

Comment on lines +41 to +46
public UserDto(User user) {
this.id = user.getId();
this.name = user.getName();
this.email = user.getEmail();
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

UserDto 생성자가 RecruitmentDetailDto와 일치하지 않습니다.

RecruitmentDetailDto의 UserDto는 개별 필드를 받는 생성자를 사용하는데, 여기서는 User 엔티티를 받습니다. 일관성을 위해 동일한 구조를 사용해야 합니다.

 public static class UserDto {
     private Long id;
     private String name;
     private String email;

-    public UserDto(User user) {
-        this.id = user.getId();
-        this.name = user.getName();
-        this.email = user.getEmail();
+    public UserDto(Long id, String name, String email) {
+        this.id = id;
+        this.name = name;
+        this.email = email;
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public UserDto(User user) {
this.id = user.getId();
this.name = user.getName();
this.email = user.getEmail();
}
}
public static class UserDto {
private Long id;
private String name;
private String email;
public UserDto(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
}
🤖 Prompt for AI Agents
In
recruitment-service/src/main/java/com/example/recruitment/dto/RecruitmentResponseDto.java
around lines 41 to 46, the UserDto constructor currently accepts a User entity,
but RecruitmentDetailDto's UserDto uses a constructor that takes individual
fields. Modify the UserDto constructor to accept the same individual fields
(e.g., id, name, email) instead of a User object to maintain consistency between
the two classes.

@Service
public class OrderClient {

private final RestTemplate restTemplate = new RestTemplate();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

RestTemplate Bean 주입을 권장합니다.

직접 RestTemplate을 인스턴스화하는 대신 Spring Bean으로 주입받는 것이 좋습니다. 이는 설정 관리와 테스트 용이성을 향상시킵니다.

다음과 같이 수정하는 것을 권장합니다:

-    private final RestTemplate restTemplate = new RestTemplate();
+    private final RestTemplate restTemplate;
+    
+    public OrderClient(RestTemplate restTemplate) {
+        this.restTemplate = restTemplate;
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private final RestTemplate restTemplate = new RestTemplate();
// Remove direct instantiation
- private final RestTemplate restTemplate = new RestTemplate();
+ private final RestTemplate restTemplate;
+
+ public OrderClient(RestTemplate restTemplate) {
+ this.restTemplate = restTemplate;
+ }
🤖 Prompt for AI Agents
In
recruitment-service/src/main/java/com/example/recruitment/service/OrderClient.java
at line 13, the RestTemplate is instantiated directly which is not recommended.
Refactor the code to inject RestTemplate as a Spring Bean by removing the direct
instantiation and adding a constructor or field injection for RestTemplate.
Ensure that a RestTemplate Bean is configured in a @Configuration class or use
the default one provided by Spring Boot for better configuration management and
easier testing.

Comment on lines +22 to 51
try {
ResponseEntity<Map> response = restTemplate.postForEntity(fullUrl, requestDto, Map.class);

if (response.getStatusCode().is2xxSuccessful()) {
Map<String, Object> responseBody = response.getBody();
if (response.getStatusCode().is2xxSuccessful()) {
Map<String, Object> responseBody = response.getBody();

if (responseBody == null || !responseBody.containsKey("data")) {
throw new RuntimeException("Order 서버 응답에 'data' 항목이 없음");
}

if (responseBody != null && responseBody.containsKey("data")) {
Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
if (data == null || !data.containsKey("orderId")) {
throw new RuntimeException("Order 서버 응답 'data'에 'orderId'가 없음");
}

if (data != null && data.containsKey("orderId")) {
return Long.valueOf(data.get("orderId").toString());
Object orderIdObj = data.get("orderId");
try {
return Long.valueOf(orderIdObj.toString());
} catch (NumberFormatException e) {
throw new RuntimeException("orderId를 Long으로 변환 실패: " + orderIdObj);
}
}

throw new RuntimeException("응답에 orderId 없음");
} else {
throw new RuntimeException("Order 서버 응답 실패: " + response.getStatusCode());
}
} catch (Exception e) {
// 서버 로깅 시스템 있다면 여기에 log.error(...) 사용 권장
System.err.println("Order 서버 호출 중 예외 발생: " + e.getMessage());
throw new RuntimeException("Order 서버 호출 실패", e);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

타입 안정성 문제를 해결해야 합니다.

Raw Map 타입 사용으로 인한 unchecked operations 경고가 발생하고 있습니다. 이는 파이프라인 경고에서도 확인됩니다.

다음과 같이 제네릭 타입을 명시하여 수정하세요:

-            ResponseEntity<Map> response = restTemplate.postForEntity(fullUrl, requestDto, Map.class);
+            ResponseEntity<Map<String, Object>> response = restTemplate.postForEntity(fullUrl, requestDto, Map.class);
             
             if (response.getStatusCode().is2xxSuccessful()) {
                 Map<String, Object> responseBody = response.getBody();

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In
recruitment-service/src/main/java/com/example/recruitment/service/OrderClient.java
around lines 22 to 51, the use of raw Map types causes unchecked operation
warnings and reduces type safety. To fix this, specify generic types for all Map
declarations and method calls, such as using Map<String, Object> instead of raw
Map. This includes the ResponseEntity declaration, responseBody, and data
variables. Adding these generic type parameters will eliminate warnings and
improve type safety.

Comment on lines 136 to 162
@PatchMapping("/{recruitmentId}/accept")
public ResponseEntity<?> acceptRecruitment(@PathVariable Long recruitmentId) {
Recruitment recruitment = recruitmentRepository.findById(recruitmentId).orElseThrow();
public ResponseEntity<ApiResponse<String>> acceptRecruitment(@PathVariable Long recruitmentId) {
Recruitment recruitment = recruitmentRepository.findById(recruitmentId)
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND));

if (!"CONFIRMED".equals(recruitment.getStatus())) {
return ResponseEntity.badRequest().body("주문 수락은 CONFIRMED 상태에서만 가능합니다.");
return ResponseEntity.badRequest()
.body(ApiResponse.fail(4001, "주문 수락은 CONFIRMED 상태에서만 가능합니다.", HttpStatus.BAD_REQUEST));
}
recruitment.setStatus("ACCEPTED");
recruitmentRepository.save(recruitment);
return ResponseEntity.ok("상태가 ACCEPTED로 변경되었습니다.");
return ResponseEntity.ok(ApiResponse.ok(null, "상태가 ACCEPTED로 변경되었습니다."));
}

// 배달 완료 상태 변경
@PatchMapping("/{recruitmentId}/deliver")
public ResponseEntity<?> completeDelivery(@PathVariable Long recruitmentId) {
Recruitment recruitment = recruitmentRepository.findById(recruitmentId).orElseThrow();
public ResponseEntity<ApiResponse<String>> completeDelivery(@PathVariable Long recruitmentId) {
Recruitment recruitment = recruitmentRepository.findById(recruitmentId)
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND));

if (!"ACCEPTED".equals(recruitment.getStatus())) {
return ResponseEntity.badRequest().body("배달 완료는 ACCEPTED 상태에서만 가능합니다.");
return ResponseEntity.badRequest()
.body(ApiResponse.fail(4002, "배달 완료는 ACCEPTED 상태에서만 가능합니다.", HttpStatus.BAD_REQUEST));
}
recruitment.setStatus("DELIVERED");
recruitmentRepository.save(recruitment);
return ResponseEntity.ok("상태가 DELIVERED로 변경되었습니다.");
return ResponseEntity.ok(ApiResponse.ok(null, "상태가 DELIVERED로 변경되었습니다."));
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

에러 코드 체계를 확인해 주세요.

현재 사용된 에러 코드(4001, 4002)가 프로젝트의 에러 코드 체계와 일치하는지 확인이 필요합니다.

ErrorCode enum에 정의된 에러 코드를 확인해 보겠습니다:

또한 상태 전환 검증 로직의 중복을 줄이기 위해 서비스 레이어에서 처리하는 것을 고려해보세요.


🏁 Script executed:

#!/bin/bash
# ErrorCode enum 파일 찾기 및 내용 확인
fd -e java "ErrorCode" -x cat {} \;

# ApiResponse.fail 메서드의 시그니처 확인
ast-grep --pattern 'class ApiResponse {
  $$$
  fail($$$) {
    $$$
  }
  $$$
}'

Length of output: 675


Error 코드 일관성 확인 및 중복 로직 개선 필요

현재 컨트롤러에서 사용 중인 에러 코드(4001, 4002)는 ErrorCode enum(2000, 2007, 2006, 3000)에 정의되어 있지 않아 프로젝트 전반의 에러 코드 체계와 일관성이 맞지 않습니다. 또한 상태 전환 검증 로직이 컨트롤러에 중복되어 있어 서비스 레이어로 이관해 재사용성을 높이는 것을 권장드립니다.

  • ErrorCode enum에 신규 상태 전환 오류 코드를 추가하거나, 기존 BAD_REQUEST(2000) 코드를 재사용하도록 수정
  • ApiResponse.fail 호출 시 코드·메시지·HTTP 상태를 enum 기반으로 통일
  • acceptRecruitment / completeDelivery의 상태 검증 로직을 서비스 레이어로 추출하여 중복 제거
🤖 Prompt for AI Agents
In
recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java
lines 136 to 162, the error codes 4001 and 4002 used in ApiResponse.fail are not
defined in the project's ErrorCode enum, causing inconsistency. To fix this,
either add new error codes for these state transition errors to the ErrorCode
enum or reuse an existing appropriate code like BAD_REQUEST(2000). Also, move
the status validation logic from the controller methods acceptRecruitment and
completeDelivery into the service layer to remove duplication and improve
reusability. Update the ApiResponse.fail calls to use the enum-based error codes
and messages consistently.

Comment on lines 73 to 94
@GetMapping("/{recruitmentId}")
public ResponseEntity<?> getRecruitmentDetail(@PathVariable Long recruitmentId) {
Recruitment recruitment = recruitmentRepository.findById(recruitmentId).orElseThrow();
public ResponseEntity<ApiResponse<RecruitmentDetailDto>> getRecruitmentDetail(@PathVariable Long recruitmentId) {
Recruitment recruitment = recruitmentRepository.findById(recruitmentId)
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND));

// ✅ 작성자 정보 → 유저 서비스에서 가져옴
RecruitmentDetailDto.UserDto writer = userClient.getUserById(recruitment.getUser().getId());

List<RecruitmentParticipant> participants =
participantRepository.findByRecruitmentId(recruitmentId);
List<User> participantUsers = participants.stream()
.map(RecruitmentParticipant::getUser)
// ✅ 참여자 정보
List<RecruitmentParticipant> participants = participantRepository.findByRecruitmentId(recruitmentId);
List<RecruitmentDetailDto.UserDto> participantUsers = participants.stream()
.map(p -> userClient.getUserById(p.getUser().getId()))
.toList();

RecruitmentDetailDto dto = new RecruitmentDetailDto();
dto.setId(recruitment.getId());
dto.setTitle(recruitment.getTitle());
dto.setDescription(recruitment.getDescription());
dto.setStatus(recruitment.getStatus());
dto.setDeadlineTime(recruitment.getDeadlineTime());
dto.setUser(recruitment.getUser());
dto.setStore(recruitment.getStore());
dto.setParticipants(participantUsers);

return ResponseEntity.ok(dto);
List<Long> orderIds = participants.stream()
.map(RecruitmentParticipant::getOrderId)
.toList();

RecruitmentDetailDto dto = new RecruitmentDetailDto(recruitment, writer, participantUsers, orderIds);

return ResponseEntity.ok(ApiResponse.ok(dto, "모집 상세 조회 성공"));
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

외부 서비스 호출에 대한 오류 처리가 필요합니다.

현재 구현에는 몇 가지 중요한 문제가 있습니다:

  1. userClient.getUserById() 호출이 실패할 경우에 대한 예외 처리가 없습니다.
  2. 참여자 수만큼 개별적으로 API를 호출하면 성능 문제가 발생할 수 있습니다 (N+1 문제).

다음과 같은 개선사항을 제안합니다:

-        // ✅ 작성자 정보 → 유저 서비스에서 가져옴
-        RecruitmentDetailDto.UserDto writer = userClient.getUserById(recruitment.getUser().getId());
+        // ✅ 작성자 정보 → 유저 서비스에서 가져옴
+        RecruitmentDetailDto.UserDto writer;
+        try {
+            writer = userClient.getUserById(recruitment.getUser().getId());
+        } catch (Exception e) {
+            throw new CustomException(ErrorCode.EXTERNAL_SERVICE_ERROR, "사용자 정보를 가져올 수 없습니다.");
+        }

         // ✅ 참여자 정보
         List<RecruitmentParticipant> participants = participantRepository.findByRecruitmentId(recruitmentId);
-        List<RecruitmentDetailDto.UserDto> participantUsers = participants.stream()
-                .map(p -> userClient.getUserById(p.getUser().getId()))
-                .toList();
+        List<Long> participantUserIds = participants.stream()
+                .map(p -> p.getUser().getId())
+                .toList();
+        
+        List<RecruitmentDetailDto.UserDto> participantUsers;
+        try {
+            // 대량 조회 API가 있다면 사용을 권장합니다
+            participantUsers = userClient.getUsersByIds(participantUserIds);
+        } catch (Exception e) {
+            throw new CustomException(ErrorCode.EXTERNAL_SERVICE_ERROR, "참여자 정보를 가져올 수 없습니다.");
+        }

UserClient에 대량 조회 API가 있는지 확인해 보겠습니다:


🏁 Script executed:

#!/bin/bash
# UserClient 인터페이스에서 대량 조회 메서드가 있는지 확인
ast-grep --pattern 'interface UserClient {
  $$$
}'

# UserClient 구현체 찾기
fd -e java -x grep -l "UserClient" {} \; | grep -v "Controller"

Length of output: 202


🏁 Script executed:

#!/bin/bash
# UserClient 인터페이스에 다중 사용자 조회 메서드 존재 여부 확인
grep -n "getUsers" recruitment-service/src/main/java/com/example/recruitment/service/UserClient.java || echo "Bulk fetch 메서드 없음"

Length of output: 145


오류 처리 및 N+1 문제 완화 적용 필요

다음 두 가지 사항을 반드시 반영해주세요:

  • 외부 서비스 호출 실패 시 CustomException(ErrorCode.EXTERNAL_SERVICE_ERROR)로 예외 처리
  • 참여자 정보를 한 번에 조회할 수 있는 bulk API가 현재 없으므로,
    1. UserClientgetUsersByIds(List<Long> ids) 메서드 추가를 검토 또는
    2. 최소한 병렬 스트림(parallelStream())과 개별 try-catch로 호출하여 전체 처리 중 한 건 실패 시에도 다른 호출이 영향을 받지 않도록 방어 코드 삽입

수정 예시:

--- a/recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java
+++ b/recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java
@@ public ResponseEntity<ApiResponse<RecruitmentDetailDto>> getRecruitmentDetail(...) {
-    RecruitmentDetailDto.UserDto writer = userClient.getUserById(recruitment.getUser().getId());
+    RecruitmentDetailDto.UserDto writer;
+    try {
+        writer = userClient.getUserById(recruitment.getUser().getId());
+    } catch (Exception e) {
+        throw new CustomException(ErrorCode.EXTERNAL_SERVICE_ERROR, "작성자 정보를 가져올 수 없습니다.");
+    }
@@
-    List<RecruitmentDetailDto.UserDto> participantUsers = participants.stream()
-            .map(p -> userClient.getUserById(p.getUser().getId()))
-            .toList();
+    List<RecruitmentDetailDto.UserDto> participantUsers;
+    List<Long> participantIds = participants.stream()
+            .map(p -> p.getUser().getId())
+            .toList();
+    try {
+        // TODO: UserClient에 bulk 조회 메서드(getUsersByIds) 구현 시 대체
+        participantUsers = participantIds.parallelStream()
+            .map(id -> {
+                try {
+                    return userClient.getUserById(id);
+                } catch (Exception e) {
+                    // 실패한 경우 null 반환 후 필터링하거나 기본 값 처리
+                    return null;
+                }
+            })
+            .filter(Objects::nonNull)
+            .toList();
+    } catch (Exception e) {
+        throw new CustomException(ErrorCode.EXTERNAL_SERVICE_ERROR, "참여자 정보를 가져올 수 없습니다.");
+    }

추가로 UserClient 인터페이스에 다음 메서드 추가를 검토해주세요:

List<RecruitmentDetailDto.UserDto> getUsersByIds(List<Long> userIds);
  • 파일: recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java
  • 파일: recruitment-service/src/main/java/com/example/recruitment/service/UserClient.java
🤖 Prompt for AI Agents
In
recruitment-service/src/main/java/com/example/recruitment/controller/RecruitmentController.java
around lines 73 to 94, the calls to userClient.getUserById() lack error handling
and cause N+1 performance issues. To fix this, wrap each external userClient
call in try-catch blocks that throw CustomException with
ErrorCode.EXTERNAL_SERVICE_ERROR on failure. To mitigate N+1, add a bulk fetch
method getUsersByIds(List<Long> ids) to UserClient and use it to retrieve all
participant users in one call instead of individual calls. Update the controller
to use this bulk method for participant user retrieval and handle exceptions
accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants