Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[YS-284] feat: 실험 공고 전체 조회 최신순/오래된순 옵션 추가 #91

Merged
merged 4 commits into from
Feb 10, 2025

Conversation

chock-cho
Copy link
Member

@chock-cho chock-cho commented Feb 10, 2025

💡 작업 내용

  • 기존의 공고 전체조회 로직인 GetExperimentPostsUseCase 에 정렬값(최신순, 오래된순)을 조회하는 기능을 추가하였습니다.

최신순 정렬 - order = DESC

공고 전체조회(DESC)

오래된순 정렬 - order = ASC

공고 전체조회(ASC)

✅ 셀프 체크리스트

  • PR 제목을 형식에 맞게 작성했나요?
  • 브랜치 전략에 맞는 브랜치에 PR을 올리고 있나요?
  • 테스트는 잘 통과했나요?
  • 빌드에 성공했나요?
  • 본인을 assign 해주세요.
  • 해당 PR에 맞는 label을 붙여주세요.

🙋🏻‍ 확인해주세요

  • 관련된 Discussion 등이 있다면 첨부해주세요

🔗 Jira 티켓


https://yappsocks.atlassian.net/browse/YS-284

Summary by CodeRabbit

  • 새로운 기능
    • 실험 게시물 API에 ‘order’ 옵션이 추가되어, 결과의 정렬 순서를 ASC 또는 DESC로 선택할 수 있습니다. (기본값: DESC)
  • 버그 수정
    • 잘못된 정렬 순서를 조기에 감지하여 오류를 반환함으로써, 보다 안정적인 데이터 조회 환경을 제공합니다.

- infrastructure 계층에서 query에 order 조건 추가
- domain 계층의 gateway에 파라미터 추가
- application 계층에서 파라미터값 추가
- presentation 계층에서의 sort 필드 추가
@chock-cho chock-cho added ✅ TEST 테스트 코드 추가 ✨ FEATURE 기능 추가 labels Feb 10, 2025
@chock-cho chock-cho self-assigned this Feb 10, 2025
Copy link

coderabbitai bot commented Feb 10, 2025

Walkthrough

이번 PR은 실험 포스트 정렬 순서를 제어하기 위해 전 계층에 "order" 파라미터를 추가하고, 해당 입력값의 유효성을 검증하는 로직을 도입합니다. ExperimentPostService에서는 getExperimentPosts 및 getMyExperimentPosts 메소드에 sort order 검증(validateSortOrder) 절차가 추가되었으며, UseCase, Gateway, Repository, Controller, Mapper, 그리고 테스트 코드에서 메소드 시그니처가 업데이트되어 order 파라미터("DESC" 기본값)를 반영하도록 수정되었습니다. 잘못된 정렬 값 입력 시 예외가 발생하여 오류를 사전에 방지합니다.

Changes

파일 경로 변경 요약
src/main/kotlin/com/dobby/backend/application/service/ExperimentPostService.kt getExperimentPosts 및 getMyExperimentPosts 메소드에 sort order 검증(validateSortOrder) 추가
src/main/kotlin/com/dobby/backend/application/usecase/experiment/GetExperimentPostsUseCase.kt
src/test/kotlin/com/dobby/backend/application/usecase/experiment/GetExperimentPostsUseCaseTest.kt
PaginationInput에 order(String, 기본값 "DESC") 파라미터 추가 및 테스트 케이스 갱신
src/main/kotlin/com/dobby/backend/domain/gateway/experiment/ExperimentPostGateway.kt
src/main/kotlin/com/dobby/backend/infrastructure/gateway/experiment/ExperimentPostGatewayImpl.kt
findExperimentPostsByCustomFilter 및 findExperimentPostsByMemberIdWithPagination 메소드 시그니처에 order 파라미터 추가
src/main/kotlin/com/dobby/backend/infrastructure/database/repository/ExperimentPostCustomRepository.kt
src/main/kotlin/com/dobby/backend/infrastructure/database/repository/ExperimentPostCustomRepositoryImpl.kt
repository 메소드에 order 파라미터 추가, 쿼리 정렬 로직(getOrderClause) 수정 및 updateExperimentPostStatus에 currentDate 파라미터 반영
src/main/kotlin/com/dobby/backend/presentation/api/controller/ExperimentPostController.kt
src/main/kotlin/com/dobby/backend/presentation/api/mapper/ExperimentPostMapper.kt
API 엔드포인트 및 페이징 매핑 함수에 order 파라미터 추가 및 수정

Sequence Diagram(s)

sequenceDiagram
  participant C as 클라이언트
  participant Ctrl as ExperimentPostController
  participant S as ExperimentPostService
  participant UC as GetExperimentPostsUseCase
  participant GW as ExperimentPostGateway
  participant Repo as ExperimentPostCustomRepository
  C->>Ctrl: GET /experiment-posts?order=...
  Ctrl->>S: getExperimentPosts(order 포함 요청)
  S->>S: validateSortOrder(order) 호출
  S->>UC: use case 호출 (order 포함)
  UC->>GW: findExperimentPostsByCustomFilter(filter, pagination, order)
  GW->>Repo: 데이터 조회 (order 포함)
  Repo-->>GW: 정렬된 결과 반환
  GW-->>UC: 결과 반환
  UC-->>S: 결과 반환
  S-->>Ctrl: 응답 반환
  Ctrl-->>C: HTTP 응답 전송
Loading

Possibly related PRs

Suggested labels

♻️ REFACTORING

Suggested reviewers

  • Ji-soo708

Poem

나는 꼬리 살랑이는 작은 토끼,
코드 숲 속을 hop hop 뛰네,
ASC와 DESC가 춤추는 사이,
order 파라미터로 길을 열어,
검증의 별빛 아래 코드는 반짝여! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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: 1

🧹 Nitpick comments (6)
src/main/kotlin/com/dobby/backend/infrastructure/database/repository/ExperimentPostCustomRepository.kt (1)

12-16: 메서드 시그니처가 일관성 있게 업데이트되었습니다.

order 파라미터가 기존 findExperimentPostsByMemberIdWithPagination 메서드와 동일한 방식으로 추가되었습니다.

order 파라미터에 대한 KDoc 문서를 추가하는 것이 좋겠습니다:

    fun findExperimentPostsByCustomFilter(
        customFilter: CustomFilter,
        pagination: Pagination,
+       /** 정렬 순서 ("ASC" 또는 "DESC") */
        order: String
    ): List<ExperimentPostEntity>?
src/main/kotlin/com/dobby/backend/application/usecase/experiment/GetExperimentPostsUseCase.kt (1)

41-45: PaginationInput에 정렬 순서가 적절하게 추가되었습니다.

기본값이 "DESC"로 설정된 것이 일반적인 사용 패턴과 일치합니다.

문자열 대신 enum을 사용하면 타입 안전성이 향상될 것 같습니다:

enum class SortOrder {
    ASC, DESC
}

data class PaginationInput(
    val page: Int = 1,
    val count: Int = 6,
    val order: SortOrder = SortOrder.DESC
)
src/main/kotlin/com/dobby/backend/application/service/ExperimentPostService.kt (1)

116-121: validateSortOrder 메서드의 반환값이 사용되지 않습니다.

메서드가 검증된 정렬 순서를 반환하고 있지만, 호출하는 곳에서 이 값을 사용하지 않습니다. 반환값이 불필요하다면 Unit을 반환하도록 수정하는 것이 좋습니다.

다음과 같이 수정을 제안합니다:

-    private fun validateSortOrder(sortOrder: String): String {
+    private fun validateSortOrder(sortOrder: String) {
-        return when (sortOrder) {
+        when (sortOrder) {
-            "ASC", "DESC" -> sortOrder
+            "ASC", "DESC" -> Unit
             else -> throw InvalidRequestValueException
         }
     }
src/main/kotlin/com/dobby/backend/presentation/api/controller/ExperimentPostController.kt (2)

158-159: 정렬 순서 파라미터가 적절히 추가되었습니다.

기본값이 "DESC"로 설정되어 있어 기존 동작과의 하위 호환성이 유지됩니다. 하지만 Swagger 문서에 정렬 순서 파라미터에 대한 설명이 누락되어 있습니다.

Operation 어노테이션의 description에 정렬 순서 파라미터에 대한 설명을 추가하는 것을 제안합니다:

     @Operation(
         summary = "공고 전체 조회 API - 필터링 + 페이지네이션 적용" ,
-        description = "사용자가 필터링한 조건에 맞는 공고 목록들을 조회합니다"
+        description = "사용자가 필터링한 조건에 맞는 공고 목록들을 조회합니다. order 파라미터로 정렬 순서를 지정할 수 있습니다 (ASC: 오래된순, DESC: 최신순)."
     )

181-181: 정렬 순서 파라미터가 적절히 추가되었습니다.

기본값이 "DESC"로 설정되어 있어 기존 동작과의 하위 호환성이 유지됩니다. 하지만 Swagger 문서에 정렬 순서 파라미터에 대한 설명이 누락되어 있습니다.

Operation 어노테이션의 description에 정렬 순서 파라미터에 대한 설명을 추가하는 것을 제안합니다:

     @Operation(
         summary = "연구자가 작성한 실험 공고 리스트 조회",
-        description = "로그인한 연구자가 작성한 실험 공고 리스트를 반환합니다"
+        description = "로그인한 연구자가 작성한 실험 공고 리스트를 반환합니다. order 파라미터로 정렬 순서를 지정할 수 있습니다 (ASC: 오래된순, DESC: 최신순)."
     )
src/main/kotlin/com/dobby/backend/infrastructure/database/repository/ExperimentPostCustomRepositoryImpl.kt (1)

139-146: getOrderClause 메서드가 잘 구현되었습니다.

정렬 순서에 따라 적절한 OrderSpecifier를 반환하도록 구현되었습니다. 하지만 이미 서비스 계층에서 검증된 값이라도 안전성을 위해 else 분기에서 기본값을 반환하는 것이 좋습니다.

다음과 같이 수정을 제안합니다:

     private fun getOrderClause(order: String): OrderSpecifier<*> {
         val post = QExperimentPostEntity.experimentPostEntity
-        return if (order == "ASC") {
-            post.createdAt.asc()
-        } else {
-            post.createdAt.desc()
-        }
+        return when (order) {
+            "ASC" -> post.createdAt.asc()
+            else -> post.createdAt.desc()
+        }
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d1f6b8a and 7417b4f.

📒 Files selected for processing (9)
  • src/main/kotlin/com/dobby/backend/application/service/ExperimentPostService.kt (1 hunks)
  • src/main/kotlin/com/dobby/backend/application/usecase/experiment/GetExperimentPostsUseCase.kt (2 hunks)
  • src/main/kotlin/com/dobby/backend/domain/gateway/experiment/ExperimentPostGateway.kt (1 hunks)
  • src/main/kotlin/com/dobby/backend/infrastructure/database/repository/ExperimentPostCustomRepository.kt (1 hunks)
  • src/main/kotlin/com/dobby/backend/infrastructure/database/repository/ExperimentPostCustomRepositoryImpl.kt (2 hunks)
  • src/main/kotlin/com/dobby/backend/infrastructure/gateway/experiment/ExperimentPostGatewayImpl.kt (1 hunks)
  • src/main/kotlin/com/dobby/backend/presentation/api/controller/ExperimentPostController.kt (1 hunks)
  • src/main/kotlin/com/dobby/backend/presentation/api/mapper/ExperimentPostMapper.kt (1 hunks)
  • src/test/kotlin/com/dobby/backend/application/usecase/experiment/GetExperimentPostsUseCaseTest.kt (6 hunks)
🧰 Additional context used
📓 Learnings (4)
📓 Common learnings
Learnt from: Ji-soo708
PR: YAPP-Github/25th-Web-Team-2-BE#53
File: src/main/kotlin/com/dobby/backend/presentation/api/mapper/ExperimentPostMapper.kt:329-329
Timestamp: 2025-01-23T05:23:06.631Z
Learning: In the ExperimentPostService class, order parameter validation is performed in the service layer through the validateSortOrder method, which ensures the value is either "ASC" or "DESC" and throws InvalidParameterException for invalid values.
src/main/kotlin/com/dobby/backend/application/service/ExperimentPostService.kt (1)
Learnt from: Ji-soo708
PR: YAPP-Github/25th-Web-Team-2-BE#53
File: src/main/kotlin/com/dobby/backend/presentation/api/mapper/ExperimentPostMapper.kt:329-329
Timestamp: 2025-01-23T05:23:06.631Z
Learning: In the ExperimentPostService class, order parameter validation is performed in the service layer through the validateSortOrder method, which ensures the value is either "ASC" or "DESC" and throws InvalidParameterException for invalid values.
src/main/kotlin/com/dobby/backend/presentation/api/mapper/ExperimentPostMapper.kt (1)
Learnt from: Ji-soo708
PR: YAPP-Github/25th-Web-Team-2-BE#53
File: src/main/kotlin/com/dobby/backend/presentation/api/mapper/ExperimentPostMapper.kt:329-329
Timestamp: 2025-01-23T05:23:06.631Z
Learning: In the ExperimentPostService class, order parameter validation is performed in the service layer through the validateSortOrder method, which ensures the value is either "ASC" or "DESC" and throws InvalidParameterException for invalid values.
src/main/kotlin/com/dobby/backend/infrastructure/database/repository/ExperimentPostCustomRepositoryImpl.kt (2)
Learnt from: chock-cho
PR: YAPP-Github/25th-Web-Team-2-BE#51
File: src/main/kotlin/com/dobby/backend/infrastructure/database/repository/ExperimentPostCustomRepositoryImpl.kt:138-182
Timestamp: 2025-01-23T08:12:48.950Z
Learning: In the experiment post system, optimistic locking is unnecessary as posts can only be modified by their original authors, making concurrent modification impossible. Over-engineering should be avoided when existing access controls provide sufficient data integrity.
Learnt from: chock-cho
PR: YAPP-Github/25th-Web-Team-2-BE#77
File: src/main/kotlin/com/dobby/backend/infrastructure/database/repository/ExperimentPostCustomRepositoryImpl.kt:213-213
Timestamp: 2025-02-04T14:53:30.154Z
Learning: The hardcoded time (8:01 AM) in `ExperimentPostCustomRepositoryImpl.lastProcessedTime` is an intentional business requirement for processing experiment posts from the previous day.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (10)
src/main/kotlin/com/dobby/backend/domain/gateway/experiment/ExperimentPostGateway.kt (1)

14-14: 게이트웨이 인터페이스가 적절하게 업데이트되었습니다.

order 파라미터가 repository 계층과 일관되게 추가되었습니다.

src/main/kotlin/com/dobby/backend/application/usecase/experiment/GetExperimentPostsUseCase.kt (1)

74-78: 게이트웨이 호출이 올바르게 업데이트되었습니다.

pagination과 함께 order 파라미터가 일관되게 전달됩니다.

src/main/kotlin/com/dobby/backend/infrastructure/gateway/experiment/ExperimentPostGatewayImpl.kt (1)

27-37: 게이트웨이 구현이 인터페이스와 일관되게 업데이트되었습니다.

order 파라미터가 repository 계층으로 올바르게 전달됩니다.

src/main/kotlin/com/dobby/backend/application/service/ExperimentPostService.kt (2)

46-47: 정렬 순서 검증이 적절히 추가되었습니다.

필터 검증 후에 정렬 순서 검증이 순차적으로 이루어지도록 잘 구현되었습니다.


108-109: 정렬 순서 검증이 적절히 추가되었습니다.

내 실험 공고 조회에도 정렬 순서 검증이 일관성 있게 적용되었습니다.

src/main/kotlin/com/dobby/backend/infrastructure/database/repository/ExperimentPostCustomRepositoryImpl.kt (2)

36-40: 메서드 시그니처가 적절히 업데이트되었습니다.

정렬 순서 파라미터가 일관성 있게 추가되었습니다.


64-68: 메서드 시그니처가 적절히 업데이트되었습니다.

정렬 순서 파라미터가 일관성 있게 추가되었습니다.

src/test/kotlin/com/dobby/backend/application/usecase/experiment/GetExperimentPostsUseCaseTest.kt (1)

98-100: Mock 설정이 적절히 업데이트되었습니다.

정렬 순서 파라미터가 올바르게 전달되도록 설정되어 있습니다.

src/main/kotlin/com/dobby/backend/presentation/api/mapper/ExperimentPostMapper.kt (2)

286-296: 정렬 파라미터가 추가된 것을 확인했습니다.

order 파라미터가 PaginationInput에 올바르게 전달되고 있습니다. 서비스 레이어에서 validateSortOrder 메소드를 통해 유효성 검증이 이루어지는 것을 확인했습니다.


435-443: 정렬 파라미터가 일관성 있게 적용되었습니다.

GetMyExperimentPostsUseCase에도 동일한 방식으로 order 파라미터가 추가되어 일관성이 유지되었습니다.

Comment on lines +39 to 40
val pagination = PaginationInput(page = 1, count = 6, order = "DESC")
val input = Input(customFilter, pagination)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

테스트 입력값이 적절히 업데이트되었습니다.

정렬 순서 파라미터가 기본값 "DESC"로 설정되어 있습니다. 하지만 "ASC" 정렬 순서에 대한 테스트 케이스가 누락되어 있습니다.

오름차순 정렬에 대한 테스트 케이스를 추가하는 것을 제안합니다:

    given("오름차순 정렬이 주어졌을 때") {
        val customFilter = CustomFilterInput(
            matchType = MatchType.ALL,
            studyTarget = null,
            locationTarget = null,
            recruitStatus = RecruitStatus.ALL
        )
        val pagination = PaginationInput(page = 1, count = 6, order = "ASC")
        val input = Input(customFilter, pagination)

        val mockPost1 = // ... create mock post with earlier date
        val mockPost2 = // ... create mock post with later date

        every {
            experimentPostGateway.findExperimentPostsByCustomFilter(
                any(),
                Pagination(pagination.page, pagination.count),
                pagination.order
            )
        } returns listOf(mockPost1, mockPost2)

        `when`("execute가 호출되면") {
            val result = useCase.execute(input)

            then("오름차순으로 정렬된 결과가 반환된다") {
                result.size shouldBe 2
                result[0].postInfo.title shouldBe mockPost1.title
                result[1].postInfo.title shouldBe mockPost2.title
            }
        }
    }

@chock-cho chock-cho requested a review from Ji-soo708 February 10, 2025 07:30
Copy link
Member

@Ji-soo708 Ji-soo708 left a comment

Choose a reason for hiding this comment

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

LGTM! 클린 아키텍처 원칙에 맞게 잘 추가해주셔서 approve합니다. 수고하셨습니다~

@chock-cho chock-cho merged commit 2a49fd2 into dev Feb 10, 2025
3 checks passed
@chock-cho chock-cho deleted the feat/YS-284 branch February 10, 2025 08:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
✨ FEATURE 기능 추가 ✅ TEST 테스트 코드 추가
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants