Skip to content

Refactor/#72 folder response#73

Merged
ramen0519 merged 2 commits intodevelopfrom
refactor/#72-folder-response
Feb 9, 2026
Merged

Refactor/#72 folder response#73
ramen0519 merged 2 commits intodevelopfrom
refactor/#72-folder-response

Conversation

@ramen0519
Copy link
Copy Markdown
Contributor

@ramen0519 ramen0519 commented Feb 9, 2026

📍 PR 타입 (하나 이상 선택)

  • 기능 추가
  • 버그 수정
  • 의존성, 환경 변수, 빌드 관련 코드 업데이트
  • 기타 사소한 수정

❗️ 관련 이슈 링크

Close #72

📌 개요

사용자 폴더 조회 응답에 저장된 뉴스, 단어 개수 추가

🔁 변경 사항

Folder Response itemCount 필드 추가
Folder Repository 메서드 ( countByFolderFolderId ) 추가
Folder Service 응답 코드 수정

📸 스크린샷

👀 기타 더 이야기해볼 점

✅ 체크 리스트

  • PR 템플릿에 맞추어 작성했어요.
  • 변경 내용에 대한 테스트를 진행했어요.
  • 프로그램이 정상적으로 동작해요.
  • PR에 적절한 라벨을 선택했어요.
  • 불필요한 코드는 삭제했어요.

Summary by CodeRabbit

릴리스 노트

  • 새로운 기능
    • 폴더 관리에서 각 폴더의 항목 개수 표시 기능이 추가되었습니다. 폴더를 조회하거나 수정할 때 폴더 내 항목의 총 개수를 확인할 수 있습니다.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 9, 2026

Walkthrough

폴더 응답 DTO에 itemCount 필드를 추가하고, 폴더 조회 및 업데이트 시 해당 폴더에 속한 항목의 개수를 함께 전달하는 리팩토링입니다. 팩토리 메서드 오버로딩과 저장소 쿼리를 통해 폴더 목록 조회 응답에 항목 개수 정보를 포함시킵니다.

Changes

Cohort / File(s) Summary
응답 DTO 확장
src/main/java/com/finsight/finsight/domain/storage/application/dto/response/FolderResponse.java
itemCount 필드 추가 및 팩토리 메서드 오버로딩. from(FolderEntity) 메서드는 itemCount = null로 설정하고, from(FolderEntity, Long itemCount) 메서드를 새로 추가하여 항목 개수를 포함할 수 있게 개선.
서비스 로직 업데이트
src/main/java/com/finsight/finsight/domain/storage/domain/service/FolderService.java
FolderItemRepository 의존성 추가. getFolders()updateFolder() 메서드에서 각 폴더별 itemCount를 계산하여 새로운 팩토리 메서드 오버로드 from(folder, itemCount)를 호출.
저장소 쿼리 추가
src/main/java/com/finsight/finsight/domain/storage/persistence/repository/FolderItemRepository.java
long countByFolderFolderId(Long folderId) 메서드 추가. Spring Data JPA 네이밍 컨벤션을 활용한 간단한 쿼리 메서드.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant FolderService
    participant FolderItemRepository
    participant FolderResponse as FolderResponse Factory
    
    Client->>FolderService: getFolders()
    FolderService->>FolderService: 폴더 목록 조회
    
    loop 각 폴더별
        FolderService->>FolderItemRepository: countByFolderFolderId(folderId)
        FolderItemRepository-->>FolderService: itemCount (Long)
        FolderService->>FolderResponse: from(folder, itemCount)
        FolderResponse-->>FolderService: FolderResponse with itemCount
    end
    
    FolderService-->>Client: List<FolderResponse> (itemCount 포함)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes


📋 리뷰 의견

좋은 점:

  • 깔끔한 설계: 팩토리 메서드 오버로딩을 통해 두 가지 사용 사례(생성 vs 조회/업데이트)를 명확히 분리한 것이 훌륭합니다. 기존 코드와의 호환성도 유지됩니다. ✨

주의할 점:

  • N+1 쿼리 패턴 확인: getFolders() 메서드에서 폴더 목록을 먼저 조회한 후, 루프를 돌며 각 폴더마다 countByFolderFolderId()를 호출하는 방식으로 보입니다. 폴더가 많으면 데이터베이스 쿼리가 폭증할 수 있으니, 향후 JOIN 또는 배치 쿼리로 최적화를 고려해 주세요.
  • null 처리: itemCount가 null일 수 있으니, API 문서나 클라이언트 처리 로직에서 이를 명확히 기재하시면 좋겠습니다.

전체적으로는 간단하고 명확한 변경으로, 리뷰 부담이 적습니다! 👍

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive PR 제목이 이슈 번호만 있고 실제 변경 내용을 구체적으로 설명하지 못하고 있습니다. 'Refactor/#72'는 번호만 있고 '폴더 응답에 itemCount 추가' 같은 실질적인 내용이 부족합니다. 제목을 '폴더 응답에 itemCount 필드 추가'와 같이 변경하여 한눈에 무엇을 했는지 알 수 있게 개선해주세요.
✅ Passed checks (4 passed)
Check name Status Explanation
Description check ✅ Passed PR 설명이 템플릿 구조를 따르고 필수 정보(이슈 링크, 개요, 변경사항)를 포함하고 있으며, 체크리스트 항목들이 대부분 완료되어 있습니다.
Linked Issues check ✅ Passed 이슈 #72의 모든 코딩 요구사항이 충족되었습니다: FolderResponse에 itemCount 필드 추가, FolderItemRepository에 countByFolderFolderId 메서드 추가, FolderService의 응답 로직 수정이 완료되었습니다.
Out of Scope Changes check ✅ Passed 모든 변경사항이 이슈 #72의 요구사항 범위 내에 있습니다. FolderResponse, FolderService, FolderItemRepository의 변경이 명확하게 폴더 목록 조회 응답에 itemCount를 추가하는 목표에 집중되어 있습니다.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/#72-folder-response

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@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: 1

🤖 Fix all issues with AI agents
In
`@src/main/java/com/finsight/finsight/domain/storage/domain/service/FolderService.java`:
- Around line 35-43: getFolders in FolderService triggers an N+1 by calling
FolderItemRepository.countByFolderFolderId for each FolderEntity; add a bulk
counting query to FolderItemRepository (e.g. a method like countByFolderIds that
returns folderId->count for a list of IDs) and change FolderService.getFolders
to: fetch folders, collect their folderIds, call the new bulk count method once,
map counts into a lookup, then stream folders and call
FolderResponse.from(folder, itemCountLookup.get(folder.getFolderId())); this
reduces queries to two and avoids the per-folder count calls.

Comment on lines 35 to 43
public List<FolderResponse> getFolders(Long userId, FolderType folderType) {
List<FolderEntity> folders = folderRepository.findByUserUserIdAndFolderTypeOrderBySortOrderAsc(userId, folderType);
return folders.stream()
.map(FolderResponse::from)
.map(folder -> {
long itemCount = folderItemRepository.countByFolderFolderId(folder.getFolderId());
return FolderResponse.from(folder, itemCount);
})
.toList();
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

⚠️ N+1 쿼리 문제: 폴더 목록 조회 시 폴더 개수만큼 추가 쿼리가 발생합니다.

현재 getFolders에서 폴더 리스트를 조회한 후, 각 폴더마다 countByFolderFolderId를 개별 호출하고 있습니다. 사용자가 폴더를 10개 가지고 있다면, 폴더 목록 조회 1회 + 카운트 조회 10회 = 총 11번의 쿼리가 실행됩니다. updateFolderOrder (Line 141)도 getFolders를 호출하므로 동일한 문제가 전파됩니다.

권장 해결 방법: 한 번의 쿼리로 모든 폴더의 아이템 개수를 한꺼번에 가져오는 방식으로 개선할 수 있습니다.

🔧 제안하는 수정 방법

1단계: FolderItemRepository에 벌크 카운트 쿼리 추가

`@Query`("SELECT fi.folder.folderId, COUNT(fi) FROM FolderItemEntity fi WHERE fi.folder.folderId IN :folderIds GROUP BY fi.folder.folderId")
List<Object[]> countByFolderIds(`@Param`("folderIds") List<Long> folderIds);

2단계: FolderService.getFolders 수정

 public List<FolderResponse> getFolders(Long userId, FolderType folderType) {
     List<FolderEntity> folders = folderRepository.findByUserUserIdAndFolderTypeOrderBySortOrderAsc(userId, folderType);
+
+    List<Long> folderIds = folders.stream()
+            .map(FolderEntity::getFolderId)
+            .toList();
+
+    Map<Long, Long> itemCountMap = folderItemRepository.countByFolderIds(folderIds).stream()
+            .collect(Collectors.toMap(
+                    row -> (Long) row[0],
+                    row -> (Long) row[1]
+            ));
+
     return folders.stream()
-            .map(folder -> {
-                long itemCount = folderItemRepository.countByFolderFolderId(folder.getFolderId());
-                return FolderResponse.from(folder, itemCount);
-            })
+            .map(folder -> FolderResponse.from(folder, itemCountMap.getOrDefault(folder.getFolderId(), 0L)))
             .toList();
 }

이렇게 하면 폴더 개수와 관계없이 항상 2번의 쿼리로 처리됩니다.

As per coding guidelines, "JPA 사용 시 N+1 문제나 불필요한 쿼리가 발생하지 않는지 체크한다."

🤖 Prompt for AI Agents
In
`@src/main/java/com/finsight/finsight/domain/storage/domain/service/FolderService.java`
around lines 35 - 43, getFolders in FolderService triggers an N+1 by calling
FolderItemRepository.countByFolderFolderId for each FolderEntity; add a bulk
counting query to FolderItemRepository (e.g. a method like countByFolderIds that
returns folderId->count for a list of IDs) and change FolderService.getFolders
to: fetch folders, collect their folderIds, call the new bulk count method once,
map counts into a lookup, then stream folders and call
FolderResponse.from(folder, itemCountLookup.get(folder.getFolderId())); this
reduces queries to two and avoids the per-folder count calls.

@ramen0519 ramen0519 merged commit e756960 into develop Feb 9, 2026
1 check passed
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.

1 participant