Skip to content

[feat] 내 피드 조회 api 개발#112

Merged
seongjunnoh merged 18 commits intodevelopfrom
feat/#110-my-feeds-show-all
Jul 30, 2025
Merged

[feat] 내 피드 조회 api 개발#112
seongjunnoh merged 18 commits intodevelopfrom
feat/#110-my-feeds-show-all

Conversation

@seongjunnoh
Copy link
Collaborator

@seongjunnoh seongjunnoh commented Jul 29, 2025

#️⃣ 연관된 이슈

closes #110

📝 작업 내용

1. 내 피드 조회 api 를 개발하였습니다.

전체적인 코드의 흐름은 #104 와 매우 유사합니다

주요 코드는 아래와 같습니다

  • FeedShowMineService
    • 내 피드 조회 api의 response를 구성하기 위해
      1. 유저가 작성한 피드 목록을 페이징 처리하여 최신순으로 조회
      2. 유저가 작성한 전체 피드 개수를 추가로 구하기
      3. 1의 조회결과를 response 로 변환
  • 내 피드 조회를 위한 QueryDSL 코드
    • 피드의 조회용 모델인 FeedQueryDto에 해당 피드의 공개/비공개 글 여부를 나타내는 isPublic 필드를 추가하였습니다
    • 전체 피드 조회 api 와 마찬가지로
      1. 조건문 + 페이징 + 정렬을 모두 처리하여 현재 페이지에서 응답해야할 FeedJpaEntity의 id값의 list를 반환
      2. 1의 결과 순서대로 FeedJpaEntity를 조회 (이때 마찬가지로 필요한 정보들을 FetchJoin으로 한번에 조회)
      3. dto로 매핑

2. 또한 Cursor 클래스의 코드를 수정하였습니다.

  • 기존 Cursor 클래스는 "Cursor 를 생성할 때 '|' 구분자를 포함하지 않는 String 타입의 단일 커서를 인자로 전달받을 경우, 내부에서 구분자가 없어 파싱 에러 (500 에러) 가 발생" 하는 이슈가 있었음
  • 따라서 String 타입의 단일 커서를 인자로 받을 경우, 내부적으로 구분자를 사용하여 파싱하지 않고, 전달받은 단일 커서를 디코딩하여 보관할 수 있도록 수정
  • 또한 Cursor.toEncodedString() 메서드를 수정하여 단일 커서를 전달받을 경우에 '|' 없이 인코딩 하도록 코드를 수정
    • 이래야 response로 넘긴 cursor를 다시 request param으로 받을 때 '|' 구분자가 없이 전달받을 수 있음

3. cors allowed origins 에 FE 주소를 추가하였습니다.

  • @heeeeyong 님의 요청을 받아 FE 로컬 개발환경 주소, FE 배포 주소를 추가하였습니다.

📸 스크린샷

💬 리뷰 요구사항

현재 내 피드 조회 api 의 response에 "해당 유저가 작성한 전체 피드 개수" 인 totalFeedCount 의 값을 포함해야합니다.
내 피드 조회를 오프셋 기반 페이징 방식으로 조회한다면 Pageable 을 활용하여 쉽게 응답할 수 있지만, 현재 커서 기반 페이징 방식으로 피드를 조회하므로 해당 데이터를 어떻게 반환할까 고민하였습니다

DB에 유저가 작성한 피드 개수를 추가로 기록, 캐싱, 윈도우 함수 사용 등의 방식을 고려했지만, 최종적으로 별도의 jpql count(*) 쿼리를 날리는 방식으로 구현하였습니다.

비록 모든 페이지마다 jpql 쿼리를 매번 날려야 하고, 전체 피드 테이블을 모두 스캔하여야 하므로 피드가 많이 쌓일 경우 성능이슈가 발생할 수도 있지만, 현재 api 개발을 빠르게 진행해야한다는 최우선 요구사항에 가장 적합한 방식이라고 생각하여 일단 jpql 쿼리를 매번 날리도록 구현하였습니다.

추후에 인덱스를 설정하거나, 다른 해결방법으로 성능 개선을 시도해보면 좋을 것 같습니다!

📌 PR 진행 시 이러한 점들을 참고해 주세요

* P1 : 꼭 반영해 주세요 (Request Changes) - 이슈가 발생하거나 취약점이 발견되는 케이스 등
* P2 : 반영을 적극적으로 고려해 주시면 좋을 것 같아요 (Comment)
* P3 : 이런 방법도 있을 것 같아요~ 등의 사소한 의견입니다 (Chore)

Summary by CodeRabbit

  • 신규 기능

    • 인증된 사용자가 자신의 피드 목록을 조회할 수 있는 새로운 API 엔드포인트(/feeds/mine)가 추가되었습니다. 해당 엔드포인트는 최신순 정렬, 전체 개수, 페이지네이션(커서 기반), 마지막 페이지 여부 등의 정보를 제공합니다.
    • 피드 데이터에 공개 여부(isPublic) 정보가 포함되어 표시됩니다.
  • 버그 수정

    • 커서 기반 페이지네이션 처리 방식이 개선되어 단일/복합 커서 구분 및 인코딩 로직이 명확해졌습니다.
  • 테스트

    • "내 피드" 조회 API의 동작과 페이지네이션, 정렬, 응답 구조를 검증하는 통합 테스트가 추가되었습니다.
  • 보안

    • CORS 허용 도메인이 명시적으로 제한되어 보안이 강화되었습니다.

@seongjunnoh seongjunnoh linked an issue Jul 29, 2025 that may be closed by this pull request
2 tasks
@coderabbitai
Copy link

coderabbitai bot commented Jul 29, 2025

"""

Walkthrough

이 PR은 "내 피드 조회" API를 새롭게 추가하고, 이를 위한 서비스, 포트, 매퍼, 응답 객체, 저장소, 컨트롤러, 통합 테스트 등을 구현합니다. 또한 Cursor 기반 페이지네이션 로직을 개선하여 단일 요소 커서 처리 방식을 명확히 하였고, 관련된 도메인과 인프라 계층의 코드도 함께 수정되었습니다.

Changes

Cohort / File(s) Change Summary
Cursor 개선
src/main/java/konkuk/thip/common/util/Cursor.java
Cursor의 인코딩/디코딩 로직 개선: 단일 요소 커서 처리 방식 변경, from 및 toEncodedString 내부 로직 수정
CORS 정책 변경
src/main/java/konkuk/thip/config/SecurityConfig.java
CORS 허용 origin을 전체에서 특정 origin 리스트로 제한
FeedQueryController 및 응답 객체 추가
src/main/java/konkuk/thip/feed/adapter/in/web/FeedQueryController.java, src/main/java/konkuk/thip/feed/adapter/in/web/response/FeedShowMineResponse.java
/feeds/mine 엔드포인트 및 응답 DTO(FeedShowMineResponse, FeedDto) 추가
Persistence 계층 확장
src/main/java/konkuk/thip/feed/adapter/out/persistence/FeedQueryPersistenceAdapter.java,
src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedJpaRepository.java,
src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepository.java,
src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepositoryImpl.java
내 피드 조회 및 카운트 관련 메서드 추가, isPublic 필드 FeedQueryDto에 반영, 커서 기반 조회 방식 개선
포트/서비스/매퍼 계층 확장
src/main/java/konkuk/thip/feed/application/port/in/FeedShowMineUseCase.java,
src/main/java/konkuk/thip/feed/application/port/out/FeedQueryPort.java,
src/main/java/konkuk/thip/feed/application/service/FeedShowMineService.java,
src/main/java/konkuk/thip/feed/application/mapper/FeedQueryMapper.java
FeedShowMineUseCase, FeedShowMineService, 매퍼 메서드, 포트 메서드 추가 및 기존 메서드 시그니처 변경
FeedQueryDto 확장
src/main/java/konkuk/thip/feed/application/port/out/dto/FeedQueryDto.java
isPublic 필드 추가
전체 피드 조회 서비스 커서 처리 개선
src/main/java/konkuk/thip/feed/application/service/BasicFeedShowAllService.java
커서 파싱 및 전달 방식 개선 (Cursor 객체 활용)
내 피드 조회 통합 테스트 추가
src/test/java/konkuk/thip/feed/adapter/in/web/FeedShowMineApiTest.java
내 피드 조회 API 통합 테스트 클래스 및 시나리오 추가

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller as FeedQueryController
    participant Service as FeedShowMineService
    participant Port as FeedQueryPort
    participant Persistence as FeedQueryPersistenceAdapter
    participant Repo as FeedQueryRepository

    Client->>Controller: GET /feeds/mine (userId, cursor)
    Controller->>Service: showMyFeeds(userId, cursor)
    Service->>Port: findMyFeedsByCreatedAt(userId, Cursor)
    Port->>Persistence: findMyFeedsByCreatedAt(userId, Cursor)
    Persistence->>Repo: findMyFeedsByCreatedAt(userId, lastCreatedAt, size)
    Repo-->>Persistence: List<FeedQueryDto>
    Persistence-->>Port: CursorBasedList<FeedQueryDto>
    Port-->>Service: CursorBasedList<FeedQueryDto>
    Service->>Port: countFeedsByUserId(userId)
    Port->>Persistence: countFeedsByUserId(userId)
    Persistence->>Repo: countFeedsByUserId(userId, StatusType.ACTIVE)
    Repo-->>Persistence: long
    Persistence-->>Port: int
    Port-->>Service: int
    Service->>Controller: FeedShowMineResponse
    Controller-->>Client: BaseResponse<FeedShowMineResponse>
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Assessment against linked issues

Objective Addressed Explanation
내 피드 조회 API 개발 (#110)
내 피드 조회 API 서비스/포트/매퍼/응답 객체 구현 (#110)
내 피드 조회 API 통합 테스트 작성 (#110)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
CORS 허용 origin 변경 (src/main/java/konkuk/thip/config/SecurityConfig.java) 내 피드 조회 API 개발과 직접적인 관련이 없는 인프라 설정 변경입니다.

Possibly related PRs

Suggested labels

🧸 현준

Suggested reviewers

  • buzz0331

Poem

🐇
내 피드 찾아 hop hop hop,
커서 타고 쏙쏙쏙!
새 API로 내 글만 콕,
테스트도 빠짐없이 톡!
오늘도 코드밭에서
토끼는 신나게 점프!
🥕
"""

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b0807ac and 72befeb.

📒 Files selected for processing (2)
  • src/main/java/konkuk/thip/feed/adapter/in/web/FeedQueryController.java (3 hunks)
  • src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepositoryImpl.java (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepositoryImpl.java
  • src/main/java/konkuk/thip/feed/adapter/in/web/FeedQueryController.java
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/#110-my-feeds-show-all

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 generate unit tests to generate unit tests for 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.

@seongjunnoh seongjunnoh requested review from buzz0331 and hd0rable and removed request for buzz0331 July 29, 2025 18:57
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: 1

🧹 Nitpick comments (9)
src/main/java/konkuk/thip/config/SecurityConfig.java (1)

91-94: URL 형식 일관성 문제

허용된 origin URL들의 형식이 일치하지 않습니다. 하나는 후행 슬래시가 있고 다른 하나는 없습니다. 이는 CORS 정책에서 문제를 일으킬 수 있습니다.

다음과 같이 일관성 있게 수정하는 것을 권장합니다:

        config.setAllowedOrigins(List.of(
                "http://localhost:5173",
-                "https://thip-git-develop-thips-projects.vercel.app/"
+                "https://thip-git-develop-thips-projects.vercel.app"
        )); // 배포 시 도메인 명시
src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedJpaRepository.java (1)

11-12: JPQL 쿼리 구현이 올바름

count 쿼리의 JPQL 문법과 파라미터 바인딩이 정확하게 구현되었습니다. 다만 호출하는 곳에서 항상 StatusType.ACTIVE를 전달하는 패턴이라면, 메서드 시그니처를 단순화하는 것도 고려해볼 수 있습니다.

선택적 개선사항: 만약 항상 ACTIVE 상태의 피드만 카운트한다면 다음과 같이 단순화할 수 있습니다:

-@Query("SELECT COUNT(f) FROM FeedJpaEntity f WHERE f.userJpaEntity.userId = :userId AND f.status = :status")
-long countFeedsByUserId(@Param("userId") Long userId, @Param("status") StatusType status);
+@Query("SELECT COUNT(f) FROM FeedJpaEntity f WHERE f.userJpaEntity.userId = :userId AND f.status = 'ACTIVE'")
+long countActiveFeedsByUserId(@Param("userId") Long userId);
src/main/java/konkuk/thip/feed/application/service/FeedShowMineService.java (1)

18-18: PAGE_SIZE 상수 중복 고려

PAGE_SIZE가 BasicFeedShowAllService와 동일하게 10으로 설정되어 있습니다. 향후 페이지 사이즈를 변경할 때 일관성을 위해 공통 상수로 추출하는 것을 고려해보세요.

공통 상수 클래스나 설정값으로 추출 고려:

// Constants 클래스나 application.yml에서 관리
private static final int PAGE_SIZE = feedProperties.getDefaultPageSize();
src/main/java/konkuk/thip/feed/adapter/in/web/response/FeedShowMineResponse.java (1)

1-23: Response 구조가 깔끔하게 구현되었습니다.

Java record를 사용한 불변 응답 객체 구현이 적절합니다. 다만 다음 사항들을 고려해보세요:

  1. contentUrlsString[] 대신 List<String>으로 변경하면 더 유연한 처리가 가능합니다.
  2. totalFeedCountint 타입인데, 대용량 데이터를 고려하면 long 타입이 더 안전합니다.
src/main/java/konkuk/thip/feed/adapter/out/persistence/FeedQueryPersistenceAdapter.java (1)

47-69: 코드 중복을 줄일 수 있습니다.

findLatestFeedsByCreatedAtfindMyFeedsByCreatedAt 메서드가 동일한 구조를 가지고 있습니다. 공통 로직을 추출하면 유지보수성이 향상됩니다.

다음과 같이 리팩터링할 수 있습니다:

private CursorBasedList<FeedQueryDto> findFeedsByCreatedAt(
        Long userId, Cursor cursor, BiFunction<Long, LocalDateTime, List<FeedQueryDto>> queryFunction) {
    LocalDateTime lastCreatedAt = cursor.isFirstRequest() ? null : cursor.getLocalDateTime(0);
    int size = cursor.getPageSize();
    
    List<FeedQueryDto> feedQueryDtos = queryFunction.apply(userId, lastCreatedAt, size);
    
    return CursorBasedList.of(feedQueryDtos, size, feedQueryDto -> {
        Cursor nextCursor = new Cursor(List.of(feedQueryDto.createdAt().toString()));
        return nextCursor.toEncodedString();
    });
}

@Override
public CursorBasedList<FeedQueryDto> findLatestFeedsByCreatedAt(Long userId, Cursor cursor) {
    return findFeedsByCreatedAt(userId, cursor, 
        (uid, lastCreatedAt, size) -> feedJpaRepository.findLatestFeedsByCreatedAt(uid, lastCreatedAt, size));
}

@Override
public CursorBasedList<FeedQueryDto> findMyFeedsByCreatedAt(Long userId, Cursor cursor) {
    return findFeedsByCreatedAt(userId, cursor,
        (uid, lastCreatedAt, size) -> feedJpaRepository.findMyFeedsByCreatedAt(uid, lastCreatedAt, size));
}
src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepositoryImpl.java (1)

226-264: 새로운 메서드가 기존 패턴을 잘 따르고 있습니다.

findMyFeedsByCreatedAt 구현이 적절합니다. 하지만 DTO 변환 로직의 중복이 많습니다.

DTO 변환 로직을 공통 메서드로 추출하면 유지보수성이 향상됩니다:

private FeedQueryDto toFeedQueryDto(FeedJpaEntity e, Boolean isPriority) {
    String[] urls = e.getContentList().stream()
            .map(ContentJpaEntity::getContentUrl)
            .toArray(String[]::new);
            
    return FeedQueryDto.builder()
            .feedId(e.getPostId())
            .creatorId(e.getUserJpaEntity().getUserId())
            .creatorNickname(e.getUserJpaEntity().getNickname())
            .creatorProfileImageUrl(e.getUserJpaEntity().getImageUrl())
            .alias(e.getUserJpaEntity().getAliasForUserJpaEntity().getValue())
            .createdAt(e.getCreatedAt())
            .isbn(e.getBookJpaEntity().getIsbn())
            .bookTitle(e.getBookJpaEntity().getTitle())
            .bookAuthor(e.getBookJpaEntity().getAuthorName())
            .contentBody(e.getContent())
            .contentUrls(urls)
            .likeCount(e.getLikeCount())
            .commentCount(e.getCommentCount())
            .isPublic(e.getIsPublic())
            .isPriorityFeed(isPriority)
            .build();
}
src/test/java/konkuk/thip/feed/adapter/in/web/FeedShowMineApiTest.java (3)

1-350: 통합 테스트가 잘 구현되었습니다.

다양한 시나리오를 커버하는 포괄적인 테스트입니다. 다만 테스트 데이터 생성 코드의 중복을 줄일 수 있습니다.

테스트 데이터 생성을 위한 헬퍼 메서드를 추가하면 가독성이 향상됩니다:

private List<FeedJpaEntity> createTestFeeds(UserJpaEntity user, BookJpaEntity book, int count) {
    List<FeedJpaEntity> feeds = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        feeds.add(feedJpaRepository.save(
            TestEntityFactory.createFeed(user, book, true, 10, 5, List.of())
        ));
    }
    return feeds;
}

private void setCreatedAt(Long feedId, LocalDateTime createdAt) {
    jdbcTemplate.update(
        "UPDATE posts SET created_at = ? WHERE post_id = ?",
        Timestamp.valueOf(createdAt), feedId
    );
}

271-274: 테스트 주석이 부정확합니다.

주석이 "내 글 & 다른 모든 유저의 공개 글을 최신순 조회"라고 되어있지만, 실제로 이 API는 "내 글만 최신순 조회"합니다.

/**
 * 정렬 조건
- * 내 글 & 다른 모든 유저의 공개 글을 최신순 조회
+ * 내 글만 최신순 조회
 */

192-193: 동일한 주석 오류가 여러 곳에 있습니다.

192-193번, 343-346번 라인에도 동일한 부정확한 주석이 있습니다.

Also applies to: 343-346

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a2b62cf and c75e284.

📒 Files selected for processing (15)
  • src/main/java/konkuk/thip/common/util/Cursor.java (1 hunks)
  • src/main/java/konkuk/thip/config/SecurityConfig.java (1 hunks)
  • src/main/java/konkuk/thip/feed/adapter/in/web/FeedQueryController.java (2 hunks)
  • src/main/java/konkuk/thip/feed/adapter/in/web/response/FeedShowMineResponse.java (1 hunks)
  • src/main/java/konkuk/thip/feed/adapter/out/persistence/FeedQueryPersistenceAdapter.java (2 hunks)
  • src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedJpaRepository.java (1 hunks)
  • src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepository.java (1 hunks)
  • src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepositoryImpl.java (3 hunks)
  • src/main/java/konkuk/thip/feed/application/mapper/FeedQueryMapper.java (2 hunks)
  • src/main/java/konkuk/thip/feed/application/port/in/FeedShowMineUseCase.java (1 hunks)
  • src/main/java/konkuk/thip/feed/application/port/out/FeedQueryPort.java (1 hunks)
  • src/main/java/konkuk/thip/feed/application/port/out/dto/FeedQueryDto.java (1 hunks)
  • src/main/java/konkuk/thip/feed/application/service/BasicFeedShowAllService.java (2 hunks)
  • src/main/java/konkuk/thip/feed/application/service/FeedShowMineService.java (1 hunks)
  • src/test/java/konkuk/thip/feed/adapter/in/web/FeedShowMineApiTest.java (1 hunks)
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: seongjunnoh
PR: THIP-TextHip/THIP-Server#93
File: src/main/java/konkuk/thip/room/adapter/out/persistence/repository/RoomQueryRepositoryImpl.java:369-388
Timestamp: 2025-07-21T08:18:15.767Z
Learning: THIP 프로젝트의 커서 페이지네이션에서는 클라이언트가 "현재 조회할 페이지의 첫 번째 레코드 정보"를 cursor로 전달하며, 서버는 해당 커서 이상(inclusive)의 데이터를 조회하도록 goe, loe를 사용하여 구현되어 있다.
Learnt from: seongjunnoh
PR: THIP-TextHip/THIP-Server#93
File: src/main/java/konkuk/thip/room/adapter/out/persistence/RoomQueryPersistenceAdapter.java:49-114
Timestamp: 2025-07-28T16:44:31.224Z
Learning: seongjunnoh는 코드 중복 문제에 대한 리팩토링 제안을 적극적으로 수용하고 함수형 인터페이스를 활용한 해결책을 선호한다.
src/main/java/konkuk/thip/feed/application/mapper/FeedQueryMapper.java (1)

Learnt from: buzz0331
PR: #78
File: src/main/java/konkuk/thip/user/application/port/out/FollowingQueryPort.java:3-3
Timestamp: 2025-07-14T18:22:56.538Z
Learning: THIP 프로젝트에서는 Query API(조회 API)에 한해서는 application 계층에서 adapter.in.web.response 패키지의 response DTO를 직접 참조하는 것을 허용함. 이는 CQRS 아키텍처에서 읽기 전용 작업의 효율성을 위한 팀 컨벤션임.

src/main/java/konkuk/thip/common/util/Cursor.java (1)

Learnt from: seongjunnoh
PR: #93
File: src/main/java/konkuk/thip/room/adapter/out/persistence/repository/RoomQueryRepositoryImpl.java:369-388
Timestamp: 2025-07-21T08:18:15.767Z
Learning: THIP 프로젝트의 커서 페이지네이션에서는 클라이언트가 "현재 조회할 페이지의 첫 번째 레코드 정보"를 cursor로 전달하며, 서버는 해당 커서 이상(inclusive)의 데이터를 조회하도록 goe, loe를 사용하여 구현되어 있다.

src/main/java/konkuk/thip/feed/application/service/BasicFeedShowAllService.java (1)

Learnt from: seongjunnoh
PR: #93
File: src/main/java/konkuk/thip/room/adapter/out/persistence/repository/RoomQueryRepositoryImpl.java:369-388
Timestamp: 2025-07-21T08:18:15.767Z
Learning: THIP 프로젝트의 커서 페이지네이션에서는 클라이언트가 "현재 조회할 페이지의 첫 번째 레코드 정보"를 cursor로 전달하며, 서버는 해당 커서 이상(inclusive)의 데이터를 조회하도록 goe, loe를 사용하여 구현되어 있다.

src/main/java/konkuk/thip/feed/adapter/out/persistence/FeedQueryPersistenceAdapter.java (1)

Learnt from: seongjunnoh
PR: #93
File: src/main/java/konkuk/thip/room/adapter/out/persistence/repository/RoomQueryRepositoryImpl.java:369-388
Timestamp: 2025-07-21T08:18:15.767Z
Learning: THIP 프로젝트의 커서 페이지네이션에서는 클라이언트가 "현재 조회할 페이지의 첫 번째 레코드 정보"를 cursor로 전달하며, 서버는 해당 커서 이상(inclusive)의 데이터를 조회하도록 goe, loe를 사용하여 구현되어 있다.

src/main/java/konkuk/thip/feed/application/port/out/FeedQueryPort.java (1)

Learnt from: seongjunnoh
PR: #43
File: src/main/java/konkuk/thip/book/application/port/out/BookCommandPort.java:0-0
Timestamp: 2025-07-03T03:05:05.031Z
Learning: THIP 프로젝트에서는 CQRS Port 분리 시 다음 컨벤션을 따름: CommandPort에는 findByXXX를 통해 도메인 엔티티를 찾아오는 메서드를 추가하고, QueryPort에는 조회 API의 response에 해당하는 데이터들을 DB로부터 조회하는 메서드를 추가함.

🧬 Code Graph Analysis (1)
src/test/java/konkuk/thip/feed/adapter/in/web/FeedShowMineApiTest.java (1)
src/test/java/konkuk/thip/common/util/TestEntityFactory.java (1)
  • TestEntityFactory (29-293)
🔇 Additional comments (15)
src/main/java/konkuk/thip/feed/application/port/out/dto/FeedQueryDto.java (1)

23-23: LGTM!

isPublic 필드 추가가 적절합니다. 필드 위치와 타입이 올바르게 정의되었습니다.

src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepository.java (1)

16-16: LGTM!

새로운 findMyFeedsByCreatedAt 메서드가 기존 인터페이스 패턴과 일관성 있게 추가되었습니다. 메서드명과 시그니처가 명확합니다.

src/main/java/konkuk/thip/feed/application/mapper/FeedQueryMapper.java (1)

5-5: LGTM!

새로운 매핑 메서드가 기존 패턴과 일관성 있게 구현되었습니다. postDate 필드 매핑이 기존 메서드와 동일한 방식으로 처리되고 있으며, Query API에서 response DTO를 직접 참조하는 것은 프로젝트 컨벤션에 부합합니다.

Also applies to: 32-36

src/main/java/konkuk/thip/feed/application/port/in/FeedShowMineUseCase.java (1)

1-9: LGTM!

새로운 Use Case 인터페이스가 클린 아키텍처 패턴에 맞게 잘 설계되었습니다. 메서드 시그니처가 커서 기반 페이지네이션과 사용자별 필터링에 적합하며, 네이밍이 명확합니다.

src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedJpaRepository.java (1)

3-3: 필요한 import 추가 확인됨

StatusType, @query, @param 등 새로운 메서드 구현에 필요한 import들이 적절히 추가되었습니다.

Also applies to: 6-7

src/main/java/konkuk/thip/feed/application/service/BasicFeedShowAllService.java (2)

3-3: Cursor 추상화 도입을 위한 import 추가

Cursor 유틸리티 클래스 사용을 위한 import가 적절히 추가되었습니다.


44-44: 커서 처리 로직이 Cursor 추상화로 개선됨

수동으로 날짜 파싱하던 방식에서 Cursor 객체를 사용하는 방식으로 리팩토링되어, 커서 기반 페이지네이션 로직이 일관성 있게 통일되었습니다. 이는 코드의 가독성과 유지보수성을 향상시킵니다.

Also applies to: 47-47

src/main/java/konkuk/thip/feed/adapter/in/web/FeedQueryController.java (2)

5-5: 새로운 의존성과 import 추가 확인됨

/feeds/mine 엔드포인트 구현을 위해 필요한 FeedShowMineUseCase와 FeedShowMineResponse import 및 의존성 주입이 적절히 추가되었습니다.

Also applies to: 8-8, 19-19


28-33: 내 피드 조회 엔드포인트가 올바르게 구현됨

새로운 /feeds/mine 엔드포인트가 기존 /feeds 엔드포인트와 일관된 패턴으로 구현되었습니다. @userid 어노테이션과 선택적 cursor 파라미터 처리가 적절하며, BaseResponse로 감싸서 반환하는 것도 프로젝트 컨벤션에 맞습니다.

src/main/java/konkuk/thip/feed/application/service/FeedShowMineService.java (3)

14-21: 서비스 클래스 구조가 잘 설계됨

@service, @requiredargsconstructor 어노테이션과 적절한 의존성 주입이 구현되었습니다. FeedShowMineUseCase 인터페이스를 구현하여 계층 분리가 올바르게 되어 있습니다.


24-45: 비즈니스 로직이 명확하게 구현됨

4단계로 나누어진 구현이 명확하고 이해하기 쉽습니다. 커서 기반 페이지네이션과 응답 매핑이 적절히 처리되었습니다.


32-32: count 쿼리 성능 고려사항

PR 목표에서 언급된 대로, 매번 별도의 count 쿼리를 실행하는 것은 대용량 데이터에서 성능 이슈가 될 수 있습니다. 현재는 개발 우선순위에 따른 구현이지만, 향후 인덱싱이나 캐싱 개선을 고려해야 합니다.

대용량 데이터 환경에서의 성능 최적화를 위한 개선 방안을 검토해보세요:

  • 인덱스 최적화
  • Redis 캐싱
  • 근사치 count 사용
  • 페이지네이션 전략 재검토
src/main/java/konkuk/thip/common/util/Cursor.java (2)

38-50: 단일 커서 처리 로직이 올바르게 개선됨

구분자('|')가 없는 단일 문자열 커서를 적절히 처리하도록 개선되었습니다. 디코딩된 문자열에 구분자가 포함되어 있는지 확인한 후, 단일 커서는 List.of(decoded)로, 복합 커서는 기존 방식대로 분할하여 처리합니다.


53-60: 인코딩 로직이 단일/복합 커서를 구분하여 처리

단일 커서는 구분자 없이 직접 인코딩하고, 복합 커서는 기존 방식대로 조인 후 인코딩하도록 개선되었습니다. 이는 PR 목표에서 언급된 단일 문자열 커서 파싱 오류를 해결합니다.

src/main/java/konkuk/thip/feed/application/port/out/FeedQueryPort.java (1)

15-19: 인터페이스 변경이 적절합니다.

커서 기반 페이지네이션으로의 전환과 새로운 메서드 추가가 일관성 있게 구현되었습니다.

Comment on lines +71 to 75
@Override
public int countFeedsByUserId(Long userId) {
// int 로 강제 형변환 해도 괜찮죠??
return (int) feedJpaRepository.countFeedsByUserId(userId, StatusType.ACTIVE);
}
Copy link

@coderabbitai coderabbitai bot Jul 29, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

int 형변환으로 인한 데이터 손실 가능성이 있습니다.

countFeedsByUserId가 long을 int로 강제 형변환하고 있습니다. 사용자의 피드 수가 Integer.MAX_VALUE를 초과하면 오버플로우가 발생합니다.

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

@Override
-public int countFeedsByUserId(Long userId) {
-    // int 로 강제 형변환 해도 괜찮죠??
-    return (int) feedJpaRepository.countFeedsByUserId(userId, StatusType.ACTIVE);
+public int countFeedsByUserId(Long userId) {
+    long count = feedJpaRepository.countFeedsByUserId(userId, StatusType.ACTIVE);
+    if (count > Integer.MAX_VALUE) {
+        throw new IllegalStateException("Feed count exceeds maximum value: " + count);
+    }
+    return (int) count;
}

또는 반환 타입을 long으로 변경하는 것도 고려해보세요.

📝 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
@Override
public int countFeedsByUserId(Long userId) {
// int 로 강제 형변환 해도 괜찮죠??
return (int) feedJpaRepository.countFeedsByUserId(userId, StatusType.ACTIVE);
}
@Override
public int countFeedsByUserId(Long userId) {
long count = feedJpaRepository.countFeedsByUserId(userId, StatusType.ACTIVE);
if (count > Integer.MAX_VALUE) {
throw new IllegalStateException("Feed count exceeds maximum value: " + count);
}
return (int) count;
}
🤖 Prompt for AI Agents
In
src/main/java/konkuk/thip/feed/adapter/out/persistence/FeedQueryPersistenceAdapter.java
around lines 71 to 75, the method countFeedsByUserId casts a long value to int,
risking data loss if the count exceeds Integer.MAX_VALUE. To fix this, either
change the return type of countFeedsByUserId to long to match the repository
method's return type or handle the long value safely without casting to int.

Copy link
Contributor

Choose a reason for hiding this comment

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

ㅋㅋㅋㅋ코래가 추천하는 방법 사용해보는 것 어떨까요 (나아아중에 count가 많아질 경우 디버깅하기 어려울수도..?)

Copy link

Choose a reason for hiding this comment

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

@buzz0331 맞습니다! 미리 체크해두면 나중에 예상치 못한 오버플로우로 인한 버그를 디버깅하는 시간을 절약할 수 있죠. 특히 사용자가 많아지고 피드 수가 증가하면 이런 방어 코드가 정말 유용할 것 같습니다.

제안한 코드로 수정하시면 문제가 발생했을 때 명확한 에러 메시지와 함께 예외가 발생해서 디버깅이 훨씬 쉬워질 거예요! 👍


🧠 Learnings used
Learnt from: buzz0331
PR: THIP-TextHip/THIP-Server#75
File: src/main/java/konkuk/thip/vote/adapter/out/persistence/VoteQueryRepositoryImpl.java:50-83
Timestamp: 2025-07-14T14:19:38.796Z
Learning: Vote와 VoteItem 엔티티는 자주 함께 사용되므로, N+1 문제를 방지하기 위해 양방향 매핑과 fetch join을 고려하는 것이 좋습니다. 특히 기록장 조회 API 등에서도 함께 사용될 가능성이 높습니다.

- 내가 작성한 피드 전체 개수는 response에서 제외
- mysql은 디폴트 모드에서는 distinct, group by 구문에서 select나 group by에 명시되지 않은 컬럼을 order by에 명시하는 것을 막음
- 하지만 기존 querydsl 코드에서는 select에 명시하지 않은 createdAt을 order by에서 사용하고 있었음
- fetchFeedIdsLatest, fetchMyFeedIdsByCreatedAt 메서드에서 필요없는 distinct 제거 -> join이 없으므로 중복 row가 발생하지 않음
- fetchFeedIdsAndPriorityByFollowingPriority 메서드에서 distinct 제거 -> following 테이블에 (user, following) 쌍이 unique 하다는 전제하에 distinct 가 없어도 중복 row가 발생하지 않음
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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c75e284 and 8a6de8f.

📒 Files selected for processing (4)
  • src/main/java/konkuk/thip/feed/adapter/in/web/response/FeedShowMineResponse.java (1 hunks)
  • src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepositoryImpl.java (3 hunks)
  • src/main/java/konkuk/thip/feed/application/service/FeedShowMineService.java (1 hunks)
  • src/test/java/konkuk/thip/feed/adapter/in/web/FeedShowMineApiTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/java/konkuk/thip/feed/application/service/FeedShowMineService.java
  • src/main/java/konkuk/thip/feed/adapter/in/web/response/FeedShowMineResponse.java
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: seongjunnoh
PR: THIP-TextHip/THIP-Server#93
File: src/main/java/konkuk/thip/room/adapter/out/persistence/repository/RoomQueryRepositoryImpl.java:369-388
Timestamp: 2025-07-21T08:18:15.767Z
Learning: THIP 프로젝트의 커서 페이지네이션에서는 클라이언트가 "현재 조회할 페이지의 첫 번째 레코드 정보"를 cursor로 전달하며, 서버는 해당 커서 이상(inclusive)의 데이터를 조회하도록 goe, loe를 사용하여 구현되어 있다.
Learnt from: seongjunnoh
PR: THIP-TextHip/THIP-Server#93
File: src/main/java/konkuk/thip/room/adapter/out/persistence/RoomQueryPersistenceAdapter.java:49-114
Timestamp: 2025-07-28T16:44:31.224Z
Learning: seongjunnoh는 코드 중복 문제에 대한 리팩토링 제안을 적극적으로 수용하고 함수형 인터페이스를 활용한 해결책을 선호한다.
🧬 Code Graph Analysis (1)
src/test/java/konkuk/thip/feed/adapter/in/web/FeedShowMineApiTest.java (1)
src/test/java/konkuk/thip/common/util/TestEntityFactory.java (1)
  • TestEntityFactory (29-293)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🔇 Additional comments (4)
src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepositoryImpl.java (2)

102-102: 기존 메서드에 isPublic 필드 추가가 적절합니다

FeedQueryDto에 isPublic 필드를 추가하는 변경사항이 일관되게 적용되었습니다.

Also applies to: 145-145


224-262: 내 피드 조회 메서드 구현이 적절합니다

기존 메서드들과 일관된 패턴으로 구현되었으며, 순서 보존 로직과 DTO 변환이 올바르게 처리되고 있습니다.

src/test/java/konkuk/thip/feed/adapter/in/web/FeedShowMineApiTest.java (2)

84-132: 기본 기능 테스트가 잘 작성되었습니다

인증된 사용자의 피드만 조회되고 다른 사용자의 피드는 제외되는 것을 올바르게 검증하고 있습니다.


328-333: 커서 테스트 구현이 적절합니다

네이티브 쿼리를 사용하여 정확한 타임스탬프를 가져오고, 이를 커서로 사용하는 방식이 올바르게 구현되었습니다.

// ACTIVE 인 feed & 내가 작성한 글 & cursorCondition
feed.status.eq(StatusType.ACTIVE),
feed.userJpaEntity.userId.eq(userId),
lastCreatedAt != null ? feed.createdAt.lt(lastCreatedAt) : Expressions.TRUE
Copy link

@coderabbitai coderabbitai bot Jul 30, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

커서 조건이 기존 패턴과 다릅니다

현재 구현은 lt (less than)를 사용하고 있는데, 기존 학습된 THIP 프로젝트의 커서 페이지네이션 패턴에서는 "현재 조회할 페이지의 첫 번째 레코드 정보"를 inclusive하게 처리하기 위해 goe/loe를 사용한다고 되어 있습니다.

동일한 생성 시간을 가진 피드가 있을 경우 누락될 수 있습니다.

다음 스크립트를 실행하여 프로젝트의 다른 커서 페이지네이션 구현을 확인해주세요:


🏁 Script executed:

#!/bin/bash
# 다른 커서 페이지네이션 구현 패턴 확인
rg -A 5 -B 5 "lastCreatedAt.*\?" --type java

Length of output: 7571


🏁 Script executed:

#!/bin/bash
# Verify the cursor pagination implementation in RoomQueryRepositoryImpl for inclusive conditions
sed -n '350,410p' src/main/java/konkuk/thip/room/adapter/out/persistence/repository/RoomQueryRepositoryImpl.java

Length of output: 1059


피드 커서 페이지네이션: 동일 createdAt 타임스탬프 레코드 누락 방지

FeedQueryRepositoryImpl의 커서 조건이 현재 feed.createdAt.lt(lastCreatedAt)만 사용하고 있어, 동일한 createdAt 값을 가진 피드를 다음 페이지에서 누락시킬 수 있습니다. RoomQueryRepositoryImpl에서 보이는 것처럼 “생성 시간 + ID” 복합 키 기반 커서 조건으로 변경해주세요.

수정 예시

  • 파일: src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepositoryImpl.java
  • 메서드: fetchMyFeedIdsByCreatedAt (및 findMyFeedsByCreatedAt 등 커서 사용하는 모든 메서드)
  1. where 절 변경
    - lastCreatedAt != null ? feed.createdAt.lt(lastCreatedAt) : Expressions.TRUE
    + lastCreatedAt != null
    +     ? feed.createdAt.lt(lastCreatedAt)
    +         .or(feed.createdAt.eq(lastCreatedAt)
    +             .and(feed.feedId.lt(lastFeedId)))
    +     : Expressions.TRUE
  2. orderBy 절에 feedId 추가
    - .orderBy(feed.createdAt.desc())
    + .orderBy(feed.createdAt.desc(), feed.feedId.desc())
  3. Cursor 객체에 lastFeedId 필드 추가 및 호출부에서 함께 전달

위와 같이 복합 키 기반으로 수정하면, 동일 타임스탬프를 가진 레코드를 누락 없이 페이징할 수 있습니다.

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

🤖 Prompt for AI Agents
In
src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepositoryImpl.java
at line 272, the cursor pagination condition uses only
feed.createdAt.lt(lastCreatedAt), which can miss records with the same createdAt
timestamp. Update the where clause to use a composite key condition combining
createdAt and feedId, such as checking if createdAt is less than lastCreatedAt
or if createdAt equals lastCreatedAt and feedId is less than lastFeedId. Also,
add feedId to the orderBy clause to maintain consistent ordering. Modify the
Cursor object to include lastFeedId and update all method calls accordingly to
pass this new parameter for accurate pagination without missing records.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

음 좋은 지적이긴 하지만, 일단 LocalDateTime 타입의 커서를 활용할 때는 단일 커서로 가도 문제없다고 생각했어.

Copy link

Choose a reason for hiding this comment

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

@seongjunnoh 네, 맞습니다. LocalDateTime의 정밀도(마이크로초 단위)를 고려하면 실제로 동일한 타임스탬프를 가질 확률이 매우 낮고, 단일 커서 방식이 구현도 간단하고 성능상 이점도 있겠네요. 비즈니스 요구사항과 데이터 특성을 고려한 합리적인 선택이라고 생각됩니다.


✏️ Learnings added
Learnt from: seongjunnoh
PR: THIP-TextHip/THIP-Server#112
File: src/main/java/konkuk/thip/feed/adapter/out/persistence/repository/FeedQueryRepositoryImpl.java:272-272
Timestamp: 2025-07-30T10:44:34.096Z
Learning: seongjunnoh는 피드 커서 페이지네이션에서 LocalDateTime 단일 커서 방식을 선호하며, 복합 키 기반 커서보다 구현 단순성과 성능을 우선시한다.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: seongjunnoh
PR: THIP-TextHip/THIP-Server#93
File: src/main/java/konkuk/thip/room/adapter/out/persistence/repository/RoomQueryRepositoryImpl.java:369-388
Timestamp: 2025-07-21T08:18:15.767Z
Learning: THIP 프로젝트의 커서 페이지네이션에서는 클라이언트가 "현재 조회할 페이지의 첫 번째 레코드 정보"를 cursor로 전달하며, 서버는 해당 커서 이상(inclusive)의 데이터를 조회하도록 goe, loe를 사용하여 구현되어 있다.

Learnt from: seongjunnoh
PR: THIP-TextHip/THIP-Server#93
File: src/main/java/konkuk/thip/room/adapter/out/persistence/RoomQueryPersistenceAdapter.java:49-114
Timestamp: 2025-07-28T16:44:31.224Z
Learning: seongjunnoh는 코드 중복 문제에 대한 리팩토링 제안을 적극적으로 수용하고 함수형 인터페이스를 활용한 해결책을 선호한다.

Copy link
Contributor

@buzz0331 buzz0331 left a comment

Choose a reason for hiding this comment

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

수고하셨습니다~~ 간단한 리뷰 하나 남겼는데 확인 부탁드릴게여!!

Comment on lines +38 to +49
if (encoded == null) {
return new Cursor(List.of(), pageSize); // 빈 커서 생성
}

String decoded = URLDecoder.decode(encoded, StandardCharsets.UTF_8);

if (!decoded.contains(JOIN_DELIMITER)) {
return new Cursor(List.of(decoded), pageSize); // 단일 커서
}

List<String> parts = Arrays.asList(decoded.split(SPLIT_DELIMITER));
return new Cursor(parts, pageSize);
return new Cursor(parts, pageSize); // 복합 커서
Copy link
Contributor

Choose a reason for hiding this comment

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

굿굿 제가 놓친 부분 고쳐주셔서 감사합니다~~ 👍🏻

Comment on lines +53 to 59
if (rawCursorList.size() == 1) { // 단일 커서
return URLEncoder.encode(rawCursorList.get(0), StandardCharsets.UTF_8);
}

// 복합 커서
String raw = String.join(JOIN_DELIMITER, rawCursorList);
return URLEncoder.encode(raw, StandardCharsets.UTF_8);
Copy link
Contributor

Choose a reason for hiding this comment

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

오호 굳이 분기처리 없을 것 같다고 생각했는데 필요없는 join 연산을 안하니 성능과 가독성 면에서 좋은 분기처리인 것 같습니다!! 👍🏻 👍🏻

Comment on lines 91 to 94
config.setAllowedOrigins(List.of(
"http://localhost:5173",
"https://thip-git-develop-thips-projects.vercel.app/"
)); // 배포 시 도메인 명시
Copy link
Contributor

Choose a reason for hiding this comment

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

LGTM

Comment on lines 238 to 261
return ordered.stream()
.map(e -> {
String[] urls = e.getContentList().stream()
.map(ContentJpaEntity::getContentUrl)
.toArray(String[]::new);
return FeedQueryDto.builder()
.feedId(e.getPostId())
.creatorId(e.getUserJpaEntity().getUserId())
.creatorNickname(e.getUserJpaEntity().getNickname())
.creatorProfileImageUrl(e.getUserJpaEntity().getImageUrl())
.alias(e.getUserJpaEntity().getAliasForUserJpaEntity().getValue())
.createdAt(e.getCreatedAt())
.isbn(e.getBookJpaEntity().getIsbn())
.bookTitle(e.getBookJpaEntity().getTitle())
.bookAuthor(e.getBookJpaEntity().getAuthorName())
.contentBody(e.getContent())
.contentUrls(urls)
.likeCount(e.getLikeCount())
.commentCount(e.getCommentCount())
.isPublic(e.getIsPublic())
// 내 피드 조회에서 priority 는 null
.build();
})
.toList();
Copy link
Contributor

Choose a reason for hiding this comment

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

p3: 이거 toFeedQueryDto 같은 메서드로 추출하는 것 어떨까요? 3번 반복되고 있는 것 같아서 가독성을 조금 해치는 것 같습니다!!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

좋습니다!! 급하게 개발한다고 신경쓰지 못했네요 반영하겠습니다!

Comment on lines +22 to +41
@Transactional(readOnly = true)
@Override
public FeedShowMineResponse showMyFeeds(Long userId, String cursor) {
// 1. 커서 생성
Cursor nextCursor = Cursor.from(cursor, PAGE_SIZE);

// 2. [최신순으로] 피드 조회 with 페이징 처리
CursorBasedList<FeedQueryDto> result = feedQueryPort.findMyFeedsByCreatedAt(userId, nextCursor);

// 3. dto -> response 변환
var feedList = result.contents().stream()
.map(feedQueryMapper::toFeedShowMineResponse)
.toList();

return new FeedShowMineResponse(
feedList,
result.nextCursor(),
!result.hasNext()
);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

LGTM

Copy link
Contributor

@buzz0331 buzz0331 left a comment

Choose a reason for hiding this comment

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

수고하셨어요! 머지하셔도 될 것 같슴당

@seongjunnoh seongjunnoh merged commit 8996eae into develop Jul 30, 2025
2 checks passed
@seongjunnoh seongjunnoh deleted the feat/#110-my-feeds-show-all branch July 30, 2025 11:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[THIP2025-165] [feat] 내 피드 조회 api 개발

2 participants