Skip to content

Conversation

@pokerbearkr
Copy link
Contributor

@pokerbearkr pokerbearkr commented Jun 24, 2025


작업 내용

  • 내 랭킹조회, 타겟 랭킹 조회 구현

변경 사항

  • ranking쪽 controller, service에 메서드 추가
  • TargetRankingResponse Dto 추가

트러블 슈팅


해결해야 할 문제


참고 사항


코드 리뷰 전 확인 체크리스트

  • 불필요한 콘솔 로그, 주석 제거
  • 커밋 메시지 컨벤션 준수 (type : )
  • 기능 정상 동작 확인

Summary by CodeRabbit

  • 신규 기능
    • 사용자의 랭킹 주변 정보를 조회할 수 있는 새로운 API 엔드포인트가 추가되었습니다. (본인 기준 및 특정 사용자 기준)
    • 랭킹 응답에 본인 여부를 구분할 수 있는 필드가 포함되어, 본인 랭킹을 시각적으로 구분할 수 있습니다.

@coderabbitai
Copy link

coderabbitai bot commented Jun 24, 2025

Walkthrough

랭킹 시스템에 사용자 중심 랭킹 조회 기능이 추가되었습니다. 새로운 DTO와 서비스 메서드가 도입되어, 지정한 사용자 또는 현재 로그인한 사용자의 랭킹 주변 정보를 조회할 수 있는 API 엔드포인트가 구현되었습니다.

Changes

파일/경로 요약 변경 내용 요약
src/main/java/org/ezcode/codetest/application/ranking/dto/TargetRankingResponse.java 사용자 랭킹 정보용 DTO TargetRankingResponse 레코드 추가
src/main/java/org/ezcode/codetest/application/ranking/service/RankingFacadeService.java getRanking(String period, Long userId) 메서드 추가, 랭킹 조회 로직 구현
src/main/java/org/ezcode/codetest/infrastructure/ranking/redis/RedisRankingService.java getRanking(String key, Long userId) 메서드 추가, Redis 기반 주변 랭킹 조회 구현
src/main/java/org/ezcode/codetest/presentation/ranking/RankingController.java /me/around, /{userId}/around GET 엔드포인트 추가, 사용자 중심 랭킹 조회 API 구현

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller
    participant FacadeService
    participant RedisRankingService
    participant DB

    Client->>Controller: GET /me/around?period=...
    Controller->>FacadeService: getRanking(period, userId)
    FacadeService->>RedisRankingService: getRanking(redisKey, userId)
    RedisRankingService->>RedisRankingService: 사용자 랭크 조회 (reverseRank)
    RedisRankingService->>RedisRankingService: 주변 랭킹 조회 (reverseRangeWithScores)
    RedisRankingService->>DB: 사용자 닉네임 일괄 조회
    RedisRankingService-->>FacadeService: TargetRankingResponse 리스트 반환
    FacadeService-->>Controller: TargetRankingResponse 리스트 반환
    Controller-->>Client: TargetRankingResponse 리스트 반환
Loading

Possibly related PRs

  • fix : rank 예약어 수정 #78: TargetRankingResponse의 필드명을 rank에서 ranks로 변경하는 등, 랭킹 응답 데이터 구조의 명명 규칙과 직접적으로 연관된 PR입니다.

Suggested labels

enhancement

Suggested reviewers

  • Kimminu7
  • minjee2758
  • thezz9
  • NCookies
  • chat26666

Poem

랭킹 옆에 토끼가 깡총,
내 랭킹, 네 랭킹, 모두 다 확인!
주변 친구들 랭킹도 한눈에 쏙,
새로운 API로 랭킹 탐험 속속.
🥕 점프하며 코드를 완성해요!

✨ 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: 0

🧹 Nitpick comments (10)
src/main/java/org/ezcode/codetest/application/ranking/dto/TargetRankingResponse.java (2)

6-6: 필드명 개선 권장

ranks 보다는 rank가 더 적절한 필드명입니다. 단수형이 일반적이고 다른 코드에서도 rank로 사용되고 있습니다.

-        int ranks,
+        int rank,

8-8: 코드 일관성을 위한 주석 언어 통일 고려

한국어 주석이 프로젝트의 다른 부분과 일관성을 유지하는지 확인해보세요. 프로젝트에서 영어 주석을 주로 사용한다면 통일하는 것이 좋겠습니다.

src/main/java/org/ezcode/codetest/application/ranking/service/RankingFacadeService.java (2)

40-40: 에러 메시지 언어 일관성 검토

한국어 에러 메시지가 프로젝트의 다른 예외 메시지들과 언어적으로 일관성을 유지하는지 확인해보세요. 국제화를 고려한다면 영어 메시지 사용을 권장합니다.


34-44: 입력 검증 강화 권장

userId가 null이거나 음수일 경우에 대한 검증을 추가하는 것이 좋겠습니다.

 public List<TargetRankingResponse> getRanking(String period, Long userId) {
+    if (userId == null || userId <= 0) {
+        throw new IllegalArgumentException("유효하지 않은 사용자 ID입니다.");
+    }
     LocalDate baseMonday = LocalDate.now().with(DayOfWeek.MONDAY);
src/main/java/org/ezcode/codetest/infrastructure/ranking/redis/RedisRankingService.java (2)

91-91: 성능 최적화 권장

스트림 내부에서 매번 reverseRank를 호출하는 것은 비효율적입니다. 이미 start, end 인덱스를 알고 있으므로 계산으로 순위를 구할 수 있습니다.

 return range.stream().map(tuple -> {
     Long id = Long.parseLong(tuple.getValue());
-    Long rank = redisTemplate.opsForZSet().reverseRank(key, tuple.getValue());
+    int currentIndex = (int) (start + Arrays.asList(range.toArray()).indexOf(tuple));
+    int calculatedRank = currentIndex + 1;
 
     return new TargetRankingResponse(
         id,
         nicknameMap.getOrDefault(id, "알 수 없음"),
-        rank != null ? rank.intValue() + 1 : -1,
+        calculatedRank,
         tuple.getScore() != null ? tuple.getScore().intValue() : 0,
         id.equals(userId)
     );
 }).sorted(Comparator.comparingInt(TargetRankingResponse::ranks)).toList();

82-87: 코드 간소화 권장

사용자 ID와 닉네임 매핑 로직을 더 간단하게 표현할 수 있습니다.

 Map<Long, String> nicknameMap = userJpaRepository.findAllById(
-        ids.stream().map(Long::parseLong).toList()
-).stream().collect(Collectors.toMap(
-        u -> u.getId(),
-        u -> u.getNickname()
-));
+        ids.stream().map(Long::parseLong).toList()
+).stream().collect(Collectors.toMap(
+        user -> user.getId(),
+        user -> user.getNickname()
+));
src/main/java/org/ezcode/codetest/presentation/ranking/RankingController.java (4)

45-46: 주석 언어 일관성 검토

한국어 주석이 프로젝트의 다른 컨트롤러 주석들과 언어적으로 일관성을 유지하는지 확인해보세요.


48-53: 입력 매개변수 검증 추가 권장

period 매개변수에 대한 검증을 컨트롤러 레벨에서 추가하는 것이 좋겠습니다. @RequestParam에 required=true를 명시하거나 validation 어노테이션을 사용해보세요.

 @GetMapping("/me/around")
 public List<TargetRankingResponse> getMyRanking(
-        @RequestParam("period") String period,
+        @RequestParam(value = "period", required = true) String period,
         @AuthenticationPrincipal AuthUser authUser
 ) {

55-61: 경로 변수 검증 강화 권장

userId 경로 변수가 유효한 양수인지 검증하는 로직을 추가하는 것이 좋겠습니다.

 @GetMapping("/{userId}/around")
 public List<TargetRankingResponse> getTargetAroundRanking(
-        @RequestParam("period") String period,
-        @PathVariable Long userId
+        @RequestParam(value = "period", required = true) String period,
+        @PathVariable @Min(1) Long userId
 ) {

@Min 어노테이션을 사용하려면 @Valid 어노테이션도 메서드에 추가해야 합니다.


47-61: API 응답 통일성 고려

다른 랭킹 엔드포인트들과 달리 이 두 엔드포인트는 ResponseEntity를 사용하지 않습니다. 일관성을 위해 ResponseEntity<List<TargetRankingResponse>>로 반환하는 것을 고려해보세요.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7a171a4 and 73b142e.

📒 Files selected for processing (4)
  • src/main/java/org/ezcode/codetest/application/ranking/dto/TargetRankingResponse.java (1 hunks)
  • src/main/java/org/ezcode/codetest/application/ranking/service/RankingFacadeService.java (2 hunks)
  • src/main/java/org/ezcode/codetest/infrastructure/ranking/redis/RedisRankingService.java (2 hunks)
  • src/main/java/org/ezcode/codetest/presentation/ranking/RankingController.java (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build

@pokerbearkr pokerbearkr merged commit b42839e into dev Jun 24, 2025
2 checks passed
@pokerbearkr pokerbearkr deleted the feat/myrank branch June 24, 2025 02:10
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.

4 participants