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

feat: 스터디 개설 V2 API 구현 #863

Merged
merged 6 commits into from
Feb 2, 2025

Conversation

uwoobeat
Copy link
Member

@uwoobeat uwoobeat commented Jan 31, 2025

🌱 관련 이슈

📌 작업 내용 및 특이사항

📝 참고사항

📚 기타

Summary by CodeRabbit

  • 새로운 기능

    • 스터디 생성 API V2 추가
    • 멘토를 통한 스터디 개설 기능 구현
    • 스터디 세션 자동 생성 및 출석 번호 랜덤 생성 지원
    • 스터디 생성 요청을 위한 데이터 구조 추가
  • 개선 사항

    • 스터디 생성 요청에 대한 유효성 검증 추가
    • 멘토 역할 자동 지정 기능 구현
  • 테스트

    • 스터디 생성 프로세스에 대한 통합 테스트 추가

@uwoobeat uwoobeat requested a review from a team as a code owner January 31, 2025 05:15
@uwoobeat uwoobeat self-assigned this Jan 31, 2025
Copy link

coderabbitai bot commented Jan 31, 2025

Walkthrough

이 풀 리퀘스트는 스터디 V2 API 개설을 위한 새로운 컨트롤러, 서비스, 저장소, DTO 및 관련 구성 요소를 도입합니다. 주요 기능은 멘토가 새로운 스터디를 생성할 수 있는 API 엔드포인트를 제공하는 것으로, 스터디 세션 생성, 멘토 역할 할당, 출석 번호 생성 등의 로직을 포함합니다.

Changes

파일 경로 변경 요약
src/main/java/com/gdschongik/gdsc/domain/studyv2/api/AdminStudyControllerV2.java 스터디 개설을 위한 REST 컨트롤러 추가
src/main/java/com/gdschongik/gdsc/domain/studyv2/application/AdminStudyServiceV2.java 스터디 생성 서비스 로직 구현
src/main/java/com/gdschongik/gdsc/domain/studyv2/dao/* 스터디 V2 관련 저장소 인터페이스 및 구현체 추가
src/main/java/com/gdschongik/gdsc/domain/studyv2/domain/RandomAttendanceNumberGenerator.java 컴포넌트 어노테이션 추가
src/main/java/com/gdschongik/gdsc/domain/studyv2/dto/request/StudyCreateRequest.java 스터디 생성 요청을 위한 DTO 레코드 추가
src/test/java/com/gdschongik/gdsc/domain/studyv2/application/AdminStudyServiceV2Test.java 스터디 생성 서비스에 대한 통합 테스트 추가

Assessment against linked issues

목표 해결 여부 설명
스터디 개설 V2 API 구현 [#859]

Possibly related PRs

Suggested labels

✨ feature

Suggested reviewers

  • Sangwook02
  • kckc0608

Poem

🐰 새로운 스터디의 문,
코드로 열리는 학습의 꿈
멘토와 학생, 함께 배우며
지식의 씨앗 뿌리는 봄
코드래빗, 환영합니다! 🌱


📜 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 18b905a and 642a670.

📒 Files selected for processing (1)
  • src/main/java/com/gdschongik/gdsc/domain/studyv2/dao/StudyV2RepositoryImpl.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/gdschongik/gdsc/domain/studyv2/dao/StudyV2RepositoryImpl.java

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

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

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: 3

🧹 Nitpick comments (6)
src/main/java/com/gdschongik/gdsc/domain/studyv2/domain/RandomAttendanceNumberGenerator.java (1)

Line range hint 17-23: 예외 처리 방식 개선을 제안드립니다.

@SneakyThrows를 사용하면 예외가 숨겨져 디버깅이 어려울 수 있습니다. 명시적인 예외 처리를 통해 코드의 안정성을 높일 것을 제안드립니다.

다음과 같이 수정하는 것을 고려해보세요:

-    @SneakyThrows
     public String generate() {
+        try {
         return String.valueOf(SecureRandom.getInstanceStrong()
                 .ints(MIN_ORIGIN, MAX_BOUND)
                 .findFirst()
                 .orElseThrow());
+        } catch (Exception e) {
+            throw new RuntimeException("출석 번호 생성 중 오류가 발생했습니다.", e);
+        }
     }
src/main/java/com/gdschongik/gdsc/domain/studyv2/application/AdminStudyServiceV2.java (2)

33-33: mentor.assignToMentor() 호출 시점과 로직을 점검하세요
이미 멘토로 지정된 사용자의 경우 예외 처리가 필요할 수 있습니다. 중복 역할 부여로 인한 예기치 않은 상태를 방지하세요.


54-54: 로그에 멘토 정보도 함께 남기는 것을 고려해보세요
스터디 ID뿐 아니라 멘토 ID나 멘토 이름 등을 함께 로깅하면 추적과 분석이 더욱 용이합니다.

src/main/java/com/gdschongik/gdsc/domain/studyv2/dao/StudyV2CustomRepository.java (1)

7-7: 메서드 명이 의도를 명확히 드러내는지 검토해보세요
“findFetchById”라는 이름은 fetch join을 한다는 의도를 어느 정도 나타내지만, 실제 사용하는 쿼리 전략에 따라 더 구체적인 명명(예: findWithSessionsById)이 필요할 수 있습니다.

src/test/java/com/gdschongik/gdsc/domain/studyv2/application/AdminStudyServiceV2Test.java (2)

34-47: 테스트 데이터 생성 중복을 제거하고 엣지 케이스 테스트를 추가해야 합니다.

테스트 코드에서 다음과 같은 개선이 필요합니다:

  1. StudyCreateRequest 생성 코드가 중복됨
  2. 경계값 테스트가 누락됨 (최소/최대 라운드 수, 유효하지 않은 기간 등)

테스트 데이터 생성을 위한 팩토리 메서드를 추가하고 경계값 테스트를 추가하는 것을 제안합니다:

private StudyCreateRequest createDefaultStudyRequest(Long mentorId, Integer totalRound) {
    return new StudyCreateRequest(
            mentorId,
            StudyType.OFFLINE,
            STUDY_TITLE,
            STUDY_DESCRIPTION,
            STUDY_DESCRIPTION_NOTION_LINK,
            STUDY_SEMESTER,
            totalRound,
            DAY_OF_WEEK,
            STUDY_START_TIME,
            STUDY_END_TIME,
            STUDY_APPLICATION_PERIOD,
            STUDY_DISCORD_CHANNEL_ID,
            STUDY_DISCORD_ROLE_ID);
}

@Test
void 최소_라운드_수로_스터디를_생성할_수_있다() {
    // given
    createRegularMember();
    var request = createDefaultStudyRequest(1L, 1);
    
    // when
    adminStudyService.createStudy(request);
    
    // then
    StudyV2 study = studyV2Repository.findFetchById(1L).orElseThrow();
    assertThat(study.getStudySessions()).hasSize(1);
}

Also applies to: 64-77, 93-106


82-87: null 체크 대신 더 구체적인 검증이 필요합니다.

출석 번호가 null이 아닌지만 확인할 것이 아니라, 출석 번호의 유효성도 함께 검증해야 합니다.

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

-            assertThat(study.getStudySessions())
-                    .extracting(StudySessionV2::getLessonAttendanceNumber)
-                    .doesNotContainNull();
+            assertThat(study.getStudySessions())
+                    .extracting(StudySessionV2::getLessonAttendanceNumber)
+                    .allMatch(number -> number >= 1000 && number <= 9999);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b66e015 and 18b905a.

📒 Files selected for processing (8)
  • src/main/java/com/gdschongik/gdsc/domain/studyv2/api/AdminStudyControllerV2.java (1 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/studyv2/application/AdminStudyServiceV2.java (1 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/studyv2/dao/StudyV2CustomRepository.java (1 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/studyv2/dao/StudyV2Repository.java (1 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/studyv2/dao/StudyV2RepositoryImpl.java (1 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/studyv2/domain/RandomAttendanceNumberGenerator.java (1 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/studyv2/dto/request/StudyCreateRequest.java (1 hunks)
  • src/test/java/com/gdschongik/gdsc/domain/studyv2/application/AdminStudyServiceV2Test.java (1 hunks)
🔇 Additional comments (3)
src/main/java/com/gdschongik/gdsc/domain/studyv2/domain/RandomAttendanceNumberGenerator.java (1)

5-5: Spring 컴포넌트 등록이 적절하게 구현되었습니다.

@Component 어노테이션을 통한 Spring Bean 등록이 잘 되어있습니다. 이를 통해 다른 서비스에서 의존성 주입이 가능해졌습니다.

Also applies to: 10-10

src/main/java/com/gdschongik/gdsc/domain/studyv2/application/AdminStudyServiceV2.java (1)

30-31: 멘토 존재 여부 이외에도 추가 검증이 필요할 수 있습니다
Member 엔티티가 이미 멘토 역할을 가지고 있는지 여부 등을 사전에 확인하여, 불필요한 로직 호출을 줄이고 데이터 무결성을 강화할 수 있는지 고려해보세요.

src/main/java/com/gdschongik/gdsc/domain/studyv2/dao/StudyV2Repository.java (1)

6-6: JpaRepository 및 CustomRepository를 함께 사용하는 설계가 좋아 보입니다
현재 설계로 기본 CRUD와 커스텀 로직을 구분하여 유지보수를 쉽게 할 수 있을 것으로 보입니다.

Comment on lines 16 to 22
public Optional<StudyV2> findFetchById(Long id) {
return Optional.ofNullable(queryFactory
.selectFrom(studyV2)
.join(studyV2.studySessions)
.fetchJoin()
.fetchOne());
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

where 절이 누락되어 잘못된 결과를 반환할 수 있습니다.

findFetchById 메서드에서 id를 기준으로 필터링하는 where 절이 누락되었습니다. 현재 구현은 데이터베이스의 첫 번째 레코드를 반환할 수 있습니다.

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

     public Optional<StudyV2> findFetchById(Long id) {
         return Optional.ofNullable(queryFactory
                 .selectFrom(studyV2)
                 .join(studyV2.studySessions)
                 .fetchJoin()
+                .where(studyV2.id.eq(id))
                 .fetchOne());
     }
📝 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 Optional<StudyV2> findFetchById(Long id) {
return Optional.ofNullable(queryFactory
.selectFrom(studyV2)
.join(studyV2.studySessions)
.fetchJoin()
.fetchOne());
}
public Optional<StudyV2> findFetchById(Long id) {
return Optional.ofNullable(queryFactory
.selectFrom(studyV2)
.join(studyV2.studySessions)
.fetchJoin()
.where(studyV2.id.eq(id))
.fetchOne());
}

Comment on lines +19 to +24
DayOfWeek dayOfWeek,
LocalTime startTime,
LocalTime endTime,
@NotNull Period applicationPeriod,
String discordChannelId,
String discordRoleId) {}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

시간 관련 필드와 Discord ID에 대한 유효성 검증이 필요합니다.

현재 구현에서 몇 가지 중요한 유효성 검증이 누락되어 있습니다:

  1. 시작 시간이 종료 시간보다 이전인지 검증
  2. Discord 채널 ID와 역할 ID의 형식 검증

다음과 같은 커스텀 유효성 검증 어노테이션 추가를 제안합니다:

@interface ValidTimeRange {
    String message() default "시작 시간은 종료 시간보다 이전이어야 합니다";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = TimeRangeValidator.class)
public @interface ValidTimeRange {
    String message() default "시작 시간은 종료 시간보다 이전이어야 합니다";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

그리고 DTO에 다음과 같이 적용:

+ @ValidTimeRange
  public record StudyCreateRequest(
          @NotNull @Positive Long mentorId,
          @NotNull StudyType type,
          @NotNull String title,
          String description,
          String descriptionNotionLink,
          @NotNull Semester semester,
          @NotNull @Positive Integer totalRound,
          DayOfWeek dayOfWeek,
          LocalTime startTime,
          LocalTime endTime,
          @NotNull Period applicationPeriod,
-         String discordChannelId,
-         String discordRoleId) {}
+         @Pattern(regexp = "^\\d{17,19}$", message = "올바른 Discord 채널 ID 형식이 아닙니다")
+         String discordChannelId,
+         @Pattern(regexp = "^\\d{17,19}$", message = "올바른 Discord 역할 ID 형식이 아닙니다")
+         String discordRoleId) {}

Comment on lines +23 to +28
@Operation(summary = "스터디 개설", description = "스터디를 개설합니다. 빈 스터디회차를 함께 생성합니다.")
@PostMapping
public ResponseEntity<Void> createStudy(@Valid @RequestBody StudyCreateRequest request) {
adminStudyServiceV2.createStudy(request);
return ResponseEntity.ok().build();
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

리소스 생성에 대한 응답을 개선해야 합니다.

현재 구현은 다음과 같은 REST API 모범 사례를 따르지 않고 있습니다:

  1. 생성된 리소스의 ID를 응답하지 않음
  2. 리소스 생성 시 적절한 HTTP 상태 코드(201 Created)를 사용하지 않음

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

-    public ResponseEntity<Void> createStudy(@Valid @RequestBody StudyCreateRequest request) {
-        adminStudyServiceV2.createStudy(request);
-        return ResponseEntity.ok().build();
+    public ResponseEntity<StudyCreateResponse> createStudy(@Valid @RequestBody StudyCreateRequest request) {
+        StudyV2 study = adminStudyServiceV2.createStudy(request);
+        return ResponseEntity
+                .created(URI.create("/admin/studies/v2/" + study.getId()))
+                .body(new StudyCreateResponse(study.getId()));
     }

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

Copy link

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

Copy link
Member

@Sangwook02 Sangwook02 left a comment

Choose a reason for hiding this comment

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

lgtm

Copy link
Member

@kckc0608 kckc0608 left a comment

Choose a reason for hiding this comment

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

lgtm

@uwoobeat uwoobeat merged commit 1f4bc90 into develop Feb 2, 2025
1 check passed
@uwoobeat uwoobeat deleted the feature/859-create-study-v2-api branch February 2, 2025 10:36
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.

✨ 스터디 개설 V2 API 구현
3 participants