Skip to content

feat: 유저 프로필에 userImageId 추가#228

Merged
yooooonshine merged 2 commits intodevelopfrom
feature/227-add-profile-image-id
Oct 26, 2025
Merged

feat: 유저 프로필에 userImageId 추가#228
yooooonshine merged 2 commits intodevelopfrom
feature/227-add-profile-image-id

Conversation

@yooooonshine
Copy link
Contributor

@yooooonshine yooooonshine commented Oct 26, 2025

개요

작업사항

  • 유저 프로필에 userImageId 추가

Summary by CodeRabbit

릴리스 노트

  • 새로운 기능
    • 프로필 조회 응답에 사용자 이미지 ID가 포함되도록 확장되었습니다.
    • 내 프로필 조회 시 이미지 ID 정보가 함께 반환됩니다.
    • 다른 사용자의 프로필 조회 시에도 이미지 ID 정보가 함께 반환됩니다.

@yooooonshine yooooonshine linked an issue Oct 26, 2025 that may be closed by this pull request
@coderabbitai
Copy link

coderabbitai bot commented Oct 26, 2025

Walkthrough

ProfileService에 UserImageEntityRepository 의존성을 추가하고, getMyProfile/getProfile에 @Transactional(readOnly = true)을 적용하며 사용자 이미지의 ID를 조회하여 각각의 응답 DTO(GetMyProfileResponse, GetProfileResponse)에 userImageId를 포함하도록 변경했습니다. 테스트 역시 해당 리포지토리 목(mock) 추가 및 스텁을 반영했습니다.

Changes

Cohort / File(s) 변경 요약
서비스: ProfileService 변경
src/main/java/hanium/modic/backend/domain/profile/service/ProfileService.java
private final UserImageEntityRepository userImageEntityRepository 추가(생성자 주입), @Transactional(readOnly = true) 추가, userImageEntityRepository.findByUserId(...).map(...).orElse(null)로 이미지 ID 조회 후 DTO에 전달
DTO: 응답 레코드 확장
src/main/java/hanium/modic/backend/web/profile/dto/GetMyProfileResponse.java, src/main/java/hanium/modic/backend/web/profile/dto/GetProfileResponse.java
각 레코드에 Long userImageId 컴포넌트 추가(생성자/접근자/JSON 노출 변경)
테스트: ProfileServiceTest 업데이트
src/test/java/hanium/modic/backend/domain/profile/ProfileServiceTest.java
@Mock private UserImageEntityRepository userImageEntityRepository; 추가, 관련 when(...) 스텁(이미지 조회) 추가 및 기존 테스트 조정

Sequence Diagram(s)

sequenceDiagram
  participant Controller
  participant ProfileService
  participant UserRepo as UserRepository
  participant ImgRepo as UserImageEntityRepository
  participant DTO

  Controller->>ProfileService: getMyProfile(userId)
  ProfileService->>UserRepo: find user by id
  ProfileService->>ImgRepo: findByUserId(userId)
  ImgRepo-->>ProfileService: Optional<UserImageEntity> (maybe empty)
  ProfileService->>DTO: new GetMyProfileResponse(..., imageId)
  ProfileService-->>Controller: GetMyProfileResponse
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • 주의할 파일/항목:
    • ProfileService에서 이미지 조회의 null/Optional 처리 일관성 및 성능(추가 쿼리) 확인
    • DTO 변경으로 인한 직렬화/호환성 영향 및 API 스펙 변경(문서/클라이언트) 점검
    • 테스트에서 목 설정이 실제 호출 경로와 일치하는지 검증

Possibly related PRs

Poem

🐰 프로필 밭에 씨앗 심네,
작은 ID 한 알 반짝이네.
찾기 쉬운 길을 새로 닦아,
삭제와 관리가 편안하네.
깡충, 코드밭에 보슬비 내리네.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title Check ✅ Passed PR 제목 "feat: 유저 프로필에 userImageId 추가"는 변경사항의 주요 내용을 명확하게 요약합니다. 코드 변경의 핵심은 GetMyProfileResponse와 GetProfileResponse DTO에 userImageId 필드를 추가하고, 이를 지원하기 위해 UserImageEntityRepository를 통해 이미지 ID를 조회하는 것입니다. 제목은 간결하고 구체적이며, 팀원이 PR 이력을 훑어볼 때 주요 변경사항을 명확히 파악할 수 있습니다.
Linked Issues Check ✅ Passed 이슈 #227의 요구사항은 "유저 프로필 조회 응답에 프로필 ID(userImageId)를 추가"하는 것입니다. PR 변경사항이 이를 완벽하게 구현합니다. UserImageEntityRepository를 주입받아 userId로 이미지 ID를 조회하고, GetMyProfileResponse와 GetProfileResponse 생성자에 userImageId 파라미터를 추가하여 응답에 포함시킵니다. 또한 테스트도 새로운 저장소 의존성을 반영하도록 업데이트되었습니다.
Out of Scope Changes Check ✅ Passed 모든 코드 변경사항이 이슈 #227의 목표와 일치하며, 범위 내에 있습니다. ProfileService에 UserImageEntityRepository 의존성 추가, getMyProfile과 getProfile 메서드에서 이미지 ID 조회 로직 추가, 응답 DTO에 userImageId 필드 추가, 테스트 업데이트 등 모든 변경사항이 userImageId를 프로필 응답에 포함시키는 단일 목표를 지원합니다. @transactional 애노테이션 추가도 읽기 전용 작업의 트랜잭션 관리를 개선하는 정당한 변경입니다.
Description Check ✅ Passed PR 설명은 저장소의 필수 템플릿 구조를 따릅니다. "개요" 섹션에서 연결된 이슈 #227을 명시하고, "작업사항" 섹션에서 변경 내용을 설명합니다. 두 필수 섹션이 모두 채워져 있으며, 각 섹션의 내용이 PR의 목표와 일치합니다. 설명이 완전하고 템플릿 요구사항을 만족합니다.
✨ 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 feature/227-add-profile-image-id

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

@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 (1)
src/main/java/hanium/modic/backend/domain/profile/service/ProfileService.java (1)

36-38: 중복 쿼리를 최적화하는 것을 권장합니다.

userImageService.createImageGetUrlOptionaluserImageEntityRepository.findByUserId 모두 동일한 UserImageEntity를 조회합니다. 이로 인해 프로필 조회 시마다 불필요한 데이터베이스 호출이 중복 발생합니다.

다음 중 하나의 방식으로 개선을 고려해보세요:

방법 1: UserImageEntity를 한 번만 조회

-		final Optional<String> userImageUrl = userImageService.createImageGetUrlOptional(user.getId());
-		final Optional<Long> userImageId = userImageEntityRepository.findByUserId(user.getId())
-			.map(UserImageEntity::getId);
+		final Optional<UserImageEntity> userImage = userImageEntityRepository.findByUserId(user.getId());
+		final Optional<String> userImageUrl = userImage.map(img -> userImageService.createImageGetUrl(img));
+		final Optional<Long> userImageId = userImage.map(UserImageEntity::getId);

방법 2: UserImageService가 ID도 함께 반환하도록 수정

// UserImageService에 새 메서드 추가
public Optional<UserImageInfo> getUserImageInfo(Long userId) {
    return userImageEntityRepository.findByUserId(userId)
        .map(entity -> new UserImageInfo(entity.getId(), createImageGetUrl(entity)));
}

record UserImageInfo(Long id, String url) {}

참고: 방법 1은 userImageService.createImageGetUrlOptional 내부 구현을 확인하여 UserImageEntity를 받는 오버로드 메서드가 있는지 검토가 필요합니다.

Also applies to: 64-66

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 70ec6e1 and 5f85fae.

📒 Files selected for processing (3)
  • src/main/java/hanium/modic/backend/domain/profile/service/ProfileService.java (6 hunks)
  • src/main/java/hanium/modic/backend/web/profile/dto/GetMyProfileResponse.java (1 hunks)
  • src/main/java/hanium/modic/backend/web/profile/dto/GetProfileResponse.java (1 hunks)
🔇 Additional comments (5)
src/main/java/hanium/modic/backend/web/profile/dto/GetProfileResponse.java (1)

14-14: 필드 추가가 적절합니다.

userImageId 필드가 레코드에 올바르게 추가되었으며, Long 타입 사용으로 null 처리가 가능합니다. @JsonInclude(NON_NULL) 설정에 따라 값이 없을 때는 JSON에서 제외됩니다.

src/main/java/hanium/modic/backend/web/profile/dto/GetMyProfileResponse.java (1)

14-14: 필드 추가가 적절합니다.

GetProfileResponse와 일관되게 userImageId 필드가 추가되었습니다. 타입과 위치가 적절합니다.

src/main/java/hanium/modic/backend/domain/profile/service/ProfileService.java (3)

6-6: 필요한 의존성이 올바르게 추가되었습니다.

@Transactional, UserImageEntity, UserImageEntityRepository 임포트 및 리포지토리 의존성 주입이 적절하게 추가되었습니다.

Also applies to: 13-13, 15-15, 28-28


31-31: 트랜잭션 추가가 적절합니다.

여러 리포지토리 호출을 포함하는 조회 메서드에 @Transactional(readOnly = true)를 추가한 것은 데이터 일관성을 보장하는 좋은 관행입니다.

Also applies to: 56-56


41-52: 응답 객체 생성이 올바릅니다.

userImageId.orElse(null)을 사용하여 새로운 필드를 응답 생성자에 전달하는 방식이 적절하며, 기존 userImageUrl 패턴과 일관성이 있습니다.

Also applies to: 69-79

@yooooonshine yooooonshine merged commit 086c7ce into develop Oct 26, 2025
1 of 2 checks passed
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 (1)
src/main/java/hanium/modic/backend/domain/profile/service/ProfileService.java (1)

37-38: userImageId 조회 로직이 올바르게 구현되었습니다.

userImageEntityRepository.findByUserId()를 사용하여 이미지 ID를 조회하고 Optional 처리를 통해 null 안전성을 확보한 구현이 정확합니다.

선택적 개선 사항: 향후 성능 최적화가 필요한 경우, UserEntity 조회 시 UserImageEntity를 fetch join하여 추가 쿼리를 줄일 수 있습니다. 하지만 단일 프로필 조회에서는 현재 구현으로도 충분합니다.

// 예시: UserEntityRepository에 fetch join 쿼리 추가 시
@Query("SELECT u FROM UserEntity u LEFT JOIN FETCH u.userImage WHERE u.id = :userId")
Optional<UserEntity> findByIdWithImage(@Param("userId") Long userId);

Also applies to: 47-47, 65-66, 75-75

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f85fae and 5797093.

📒 Files selected for processing (2)
  • src/main/java/hanium/modic/backend/domain/profile/service/ProfileService.java (6 hunks)
  • src/test/java/hanium/modic/backend/domain/profile/ProfileServiceTest.java (4 hunks)
🔇 Additional comments (3)
src/test/java/hanium/modic/backend/domain/profile/ProfileServiceTest.java (1)

24-24: 목(mock) 추가가 적절합니다.

새로운 의존성 UserImageEntityRepository에 대한 목 설정이 올바르게 추가되었습니다.

Also applies to: 44-45

src/main/java/hanium/modic/backend/domain/profile/service/ProfileService.java (2)

6-6: 읽기 전용 트랜잭션 적용이 적절합니다.

@Transactional(readOnly = true) 어노테이션을 프로필 조회 메서드에 추가한 것은 좋은 개선입니다. 읽기 전용 트랜잭션은 성능 최적화와 의도 명시에 도움이 됩니다.

Also applies to: 31-31, 56-56


13-13: 새로운 의존성 추가가 올바릅니다.

UserImageEntityUserImageEntityRepository 추가가 적절하게 이루어졌습니다. 프로필 이미지 ID를 조회하기 위한 필수 의존성입니다.

Also applies to: 15-15, 28-28

when(postRepository.countByUserId(1L)).thenReturn(5L);
when(followRepository.countByMyId(1L)).thenReturn(3L);
when(followRepository.countByFollowingId(1L)).thenReturn(7L);
when(userImageEntityRepository.findByUserId(1L)).thenReturn(Optional.empty());
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

테스트에서 userImageId 필드 검증이 누락되었습니다.

테스트가 userImageEntityRepository를 스텁(stub)하고 있지만, 응답 객체의 userImageId 필드를 실제로 검증하지 않습니다. 또한 이미지가 존재하는 경우(non-empty Optional)에 대한 테스트 케이스가 없습니다.

다음 스크립트를 실행하여 응답 DTO에 userImageId 필드가 있는지 확인하세요:

테스트를 개선하기 위해 다음을 제안합니다:

  1. 기존 테스트에 userImageId 검증 추가:
 		assertThat(response.followerCount()).isEqualTo(7L);
 		assertThat(response.coin()).isEqualTo(0L);
+		assertThat(response.userImageId()).isNull();
  1. 이미지가 존재하는 경우를 테스트하는 새로운 테스트 케이스 추가를 고려하세요.

Also applies to: 86-86


🏁 Script executed:

#!/bin/bash
# GetMyProfileResponse와 GetProfileResponse에 userImageId 필드가 있는지 확인
ast-grep --pattern $'record GetMyProfileResponse($$$, Long userImageId, $$$) {}'
ast-grep --pattern $'record GetProfileResponse($$$, Long userImageId, $$$) {}'

Length of output: 0


추가 정보를 수집하기 위해 코드베이스를 더 깊이 있게 검색하겠습니다.


---

🏁 Script executed:

```shell
#!/bin/bash
# GetMyProfileResponse와 GetProfileResponse 정의 찾기
echo "=== Searching for GetMyProfileResponse ==="
rg -n "class GetMyProfileResponse|record GetMyProfileResponse|interface GetMyProfileResponse" -A 5

echo "=== Searching for GetProfileResponse ==="
rg -n "class GetProfileResponse|record GetProfileResponse|interface GetProfileResponse" -A 5

echo "=== Searching for userImageId field ==="
rg -n "userImageId" -C 2

Length of output: 4908


테스트 파일을 검토하여 실제 검증 상태를 확인하겠습니다.


🏁 Script executed:

#!/bin/bash
# ProfileServiceTest.java의 전체 내용 확인 (특히 59번과 86번 라인)
echo "=== ProfileServiceTest.java content around line 59 ==="
sed -n '45,75p' src/test/java/hanium/modic/backend/domain/profile/ProfileServiceTest.java

echo ""
echo "=== ProfileServiceTest.java content around line 86 ==="
sed -n '75,100p' src/test/java/hanium/modic/backend/domain/profile/ProfileServiceTest.java

echo ""
echo "=== Check for userImageId assertions in test ==="
rg -n "userImageId" src/test/java/hanium/modic/backend/domain/profile/ProfileServiceTest.java

Length of output: 2238


테스트에서 userImageId, hasUserImage, userImageUrl 필드 검증이 누락되었습니다.

검증 결과, userImageId 필드가 응답 DTO에 실제로 존재하며 ProfileService에서 데이터베이스 조회 결과를 매핑하고 있음이 확인되었습니다. 그러나 현재 테스트는 이 필드들을 전혀 검증하고 있지 않습니다.

필요한 개선사항:

  1. 기존 테스트에 누락된 필드 검증 추가 (line 59, 86):

    • assertThat(response.userImageId()).isNull();
    • assertThat(response.hasUserImage()).isFalse();
    • assertThat(response.userImageUrl()).isNull();
  2. 이미지가 존재하는 경우에 대한 추가 테스트 케이스 작성:

    • Optional이 비어있지 않은 경우의 시나리오를 테스트하여 userImageId가 올바르게 매핑되는지 검증
🤖 Prompt for AI Agents
In src/test/java/hanium/modic/backend/domain/profile/ProfileServiceTest.java
around lines 59 and 86, the test currently stubs
userImageEntityRepository.findByUserId(1L) to return Optional.empty() but does
not assert the userImageId, hasUserImage, and userImageUrl fields on the
response; add assertions after the call at line 59:
assertThat(response.userImageId()).isNull();
assertThat(response.hasUserImage()).isFalse();
assertThat(response.userImageUrl()).isNull(); and similarly update the
assertions at line 86 if applicable; additionally add a new test case that stubs
findByUserId to return a non-empty Optional with a UserImageEntity and asserts
that response.userImageId() equals the entity id, response.hasUserImage()
isTrue, and response.userImageUrl() equals the expected URL to verify correct
mapping.

@yooooonshine yooooonshine deleted the feature/227-add-profile-image-id branch October 26, 2025 11:51
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.

유저 프로필에 ID 반환

1 participant