Skip to content

[Refactor] 프로필 페이지 Redirect 로직 간소화#390

Merged
Chiman2937 merged 4 commits intomainfrom
chiyoung-refactor/profile-page
Feb 22, 2026
Merged

[Refactor] 프로필 페이지 Redirect 로직 간소화#390
Chiman2937 merged 4 commits intomainfrom
chiyoung-refactor/profile-page

Conversation

@Chiman2937
Copy link
Member

@Chiman2937 Chiman2937 commented Feb 21, 2026

📝 변경 사항

프로필 페이지 리팩토링 변경사항

브랜치: chiyoung-refactor/profile-page
커밋 범위: 692f496 ~ 8746c2e (3개 커밋)
변경 파일: 7개 (9 additions, 47 deletions)


커밋 히스토리

커밋 메시지
692f496 fix: profile page 로직 수정
be1ffe8 fix: 채팅 페이지 - getMeSkipRedirect 대신 getMe API로 수정
8746c2e fix: 유저 정보 API - useQuery 대신 useSuspenseQuery로 수정, getMeSkipRedirect 삭제

1. getMeSkipRedirect 삭제

user-servicegetMeSkipRedirect 메서드 및 관련 훅(useUserGetMeSkipRedirect)을 완전히 삭제.

삭제 배경

기존에 getMeSkipRedirect가 필요했던 이유는, 서버 컴포넌트에서 발생한 API 요청에 대해 refresh가 정상 동작하지 않아 별도의 API 함수를 만들어 인증 실패 시 리다이렉트를 건너뛰도록 처리했기 때문. 이전 리팩토링에서 refresh 로직이 proxy.ts(미들웨어)로 이관되면서 서버 요청에서도 refresh가 정상 동작하게 되었으므로, getMeSkipRedirect의 존재 이유가 사라짐.

삭제된 코드

// src/api/service/user-service/index.ts - 삭제
getMeSkipRedirect: async () => {
  return baseAPI.get<User>(`/api/v1/users/me`);
},

// src/hooks/use-user/use-user-get-me/index.ts - 삭제
export const useUserGetMeSkipRedirect = () => {
  const { isAuthenticated } = useAuth();
  const query = useQuery({
    queryKey: userKeys.me(),
    queryFn: () => API.userService.getMeSkipRedirect(),
    retry: false,
    enabled: isAuthenticated,
  });
  return query;
};

페이지별 대응

페이지 Before After 사유
채팅 (message/chat/[roomId]) getMeSkipRedirect() getMe() 보호된 경로이므로 accessToken 없으면 로그인 리다이렉트됨. 유저정보가 없을 일이 없어 안전
메시지 목록 (message/page) getMeSkipRedirect() getMe() 동일하게 보호된 경로
프로필 레이아웃 (profile/[userId]/layout) getMeSkipRedirect() getMe() 로그아웃 상태에서도 접근 가능하므로 .catch(() => null) 유지

2. 프로필 페이지 로직 간소화

src/app/(user)/profile/[userId]/page.tsx에서 본인 프로필 접근 시 /mypage로 리다이렉트하던 로직을 삭제.

Before

const ProfilePage = ({ params }: Props) => {
  const router = useRouter();
  const { userId: id } = use(params);
  const userId = Number(id);

  const { data: user } = useGetUser({ userId });
  const { data: me } = useUserGetMeSkipRedirect();

  useEffect(() => {
    if (user?.userId === me?.userId) {
      router.replace('/mypage');
    }
  }, [me?.userId, router, user?.userId]);

  if (!user) return null;

  return <ProfileInfo user={user} />;
};

After

const ProfilePage = ({ params }: Props) => {
  const { userId: id } = use(params);
  const userId = Number(id);

  const { data: user } = useGetUser({ userId });

  return <ProfileInfo user={user} />;
};

삭제된 항목

  • useRouter import 및 사용
  • useEffect 내 본인 프로필 → /mypage 리다이렉트 로직
  • useUserGetMeSkipRedirect 훅 사용
  • if (!user) return null 가드 (useSuspenseQuery 사용으로 불필요)

3. useQuery → useSuspenseQuery 변경

useGetUser, useUserGetMe 훅에서 useQueryuseSuspenseQuery로 변경.

// Before
import { useQuery } from '@tanstack/react-query';
const query = useQuery({ ... });

// After
import { useSuspenseQuery } from '@tanstack/react-query';
const query = useSuspenseQuery({ ... });

useSuspenseQuery는 데이터가 로딩 중일 때 컴포넌트를 suspend시켜 상위 Suspense boundary에서 처리하므로, 컴포넌트 내에서 isLoading 체크나 if (!data) return null 같은 가드가 불필요해짐.

영향받은 훅

파일
useUserGetMe src/hooks/use-user/use-user-get-me/index.ts
useGetUser src/hooks/use-user/use-user-get/index.ts

변경된 파일 목록

파일 변경 유형
src/api/service/user-service/index.ts 수정 (getMeSkipRedirect 삭제)
src/app/(user)/profile/[userId]/layout.tsx 수정 (getMe로 변경)
src/app/(user)/profile/[userId]/page.tsx 수정 (mypage 리다이렉트 로직 삭제, 간소화)
src/app/message/chat/[roomId]/page.tsx 수정 (getMe로 변경)
src/app/message/page.tsx 수정 (getMe로 변경)
src/hooks/use-user/use-user-get-me/index.ts 수정 (useUserGetMeSkipRedirect 삭제, useSuspenseQuery 변경)
src/hooks/use-user/use-user-get/index.ts 수정 (useSuspenseQuery 변경)

🔗 관련 이슈

Closes #


🧪 테스트 방법

  • 수동 테스트 검증(로컬 환경)
  • 유닛 테스트 검증
  • 통합 테스트 검증

📸 스크린샷 (선택)


📋 체크리스트

  • 관련 문서를 업데이트했습니다 (필요한 경우)
  • 테스트를 추가/수정했습니다 (필요한 경우)
  • Breaking change가 있다면 명시했습니다

💬 추가 코멘트


CodeRabbit Review는 자동으로 실행되지 않습니다.

Review를 실행하려면 comment에 아래와 같이 작성해주세요

@coderabbitai review

Summary by CodeRabbit

릴리스 노트

  • 버그 수정

    • 프로필 이미지, 상태 메시지, MBTI 정보가 누락된 경우 안정적으로 처리되도록 개선했습니다.
  • 개선 사항

    • 사용자 인증 시스템을 최적화하여 프로필 페이지 로딩 성능을 향상시켰습니다.
    • 프로필 페이지 렌더링 흐름을 단순화했습니다.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 21, 2026

Walkthrough

사용자 서비스에서 getMeSkipRedirect() 메서드를 제거하고 모든 호출을 getMe()로 대체했습니다. 또한 useUserGetMeSkipRedirect 훅을 제거하고, 두 개의 쿼리 훅을 useSuspenseQuery로 변경하며 사용자 프로필 필드에 대한 데이터 정규화를 추가했습니다.

Changes

Cohort / File(s) Summary
API 서비스 레이어
src/api/service/user-service/index.ts
공개 메서드 getMeSkipRedirect() 제거; getMe() 메서드는 유지.
프로필 페이지
src/app/(user)/profile/[userId]/layout.tsx, src/app/(user)/profile/[userId]/page.tsx
getMeSkipRedirect() 호출을 getMe()로 변경 및 클라이언트 라우팅/사용자 identity 비교 로직 제거.
메시지 페이지
src/app/message/chat/[roomId]/page.tsx, src/app/message/page.tsx
API.userService.getMeSkipRedirect()API.userService.getMe()로 변경; null 처리 개선.
사용자 훅
src/hooks/use-user/use-user-get-me/index.ts, src/hooks/use-user/use-user-get/index.ts
useUserGetMeSkipRedirect 훅 제거; useQuery에서 useSuspenseQuery로 변경; 프로필 필드 정규화 추가.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • PR #218: getMe 엔드포인트로의 호출 전환 및 getMeSkipRedirect 제거로 동일한 API 레벨의 변경을 직접 보완합니다.
  • PR #175: 동일한 사용자 훅 파일(src/hooks/use-user/use-user-get/index.ts)을 수정하여 null 필드를 빈 문자열로 정규화하고 사용자 서비스 exports를 변경합니다.

Suggested labels

Ready For Review!

Suggested reviewers

  • wooktori

Poem

🐰 건너뛴 리다이렉트는 이제 그만,
깔끔한 getMe로 새로운 길을 열었네.
의심의 여지 없이 사용자를 찾아내고,
Suspense는 기다림을 우아하게 만들고,
빈 문자열로 null을 소리 없이 감싼다. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description check ✅ Passed PR 설명은 템플릿 구조를 따르고 상세한 변경사항, 커밋 히스토리, 파일별 영향을 제공하지만 테스트 항목이 모두 미체크 상태이고 관련 이슈 번호가 비어있습니다.
Title check ✅ Passed 제목이 변경사항의 핵심을 명확하게 반영하고 있습니다. 프로필 페이지의 리다이렉트 로직 간소화라는 주요 목표를 정확하게 설명합니다.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chiyoung-refactor/profile-page

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.

@github-actions
Copy link

github-actions bot commented Feb 21, 2026

🎨 Storybook Report

변경 사항이 없습니다

모든 Story가 이전 빌드와 동일합니다.

Status Storybook Build Log Updated (UTC)
✅ Unchanged View Storybook View Build 2026-02-21 14:15:09

@Chiman2937
Copy link
Member Author

@coderabbitai review

@github-actions
Copy link

github-actions bot commented Feb 21, 2026

🎭 Playwright Report

E2E Test가 성공적으로 완료되었습니다.

Test 요약 내용을 확인해주세요.

Status Build Log Updated (UTC)
✅ Ready View Build 2026-02-21 14:16:13

📊 Test Summary

  • ✅ Passed: 3
  • ❌ Failed: 0
  • ⏱️ Duration: 35.0s

📜 Test Details

✅ Passed Tests (3)
  • profile.test.ts (3)
    • [chromium] 존재하지 않는 프로필 페이지로 접속 시 404 redirect 되는 지 테스트
    • [firefox] 존재하지 않는 프로필 페이지로 접속 시 404 redirect 되는 지 테스트
    • [webkit] 존재하지 않는 프로필 페이지로 접속 시 404 redirect 되는 지 테스트

@github-actions
Copy link

github-actions bot commented Feb 21, 2026

🚀 PR Preview Report

Build가 성공적으로 완료되었습니다.

Preview에서 변경사항을 확인하세요.

Status Preview Build Log Updated (UTC)
✅ Ready Visit Preview View Logs 2026-02-21 14:15:54

@github-actions
Copy link

github-actions bot commented Feb 21, 2026

📊 Coverage Report

Status Build Log Updated (UTC)
✅ Ready View Build 2026-02-21 14:14:45

📉 #390main에 병합하면 coverage가 0.07% 감소합니다.

Coverage 요약

@@             Coverage Diff             @@
##             main     #390       +/-   ##
===========================================
- Coverage   35.47%   35.40%    -0.07%     
===========================================
  Files         262      262         0     
  Lines       12143    12119       -24     
  Branches      468      467        -1     
===========================================
- Hits         4308     4291       -17     
- Misses       7835     7828        -7     

영향받은 파일

파일 Coverage 변화
/home/runner/work/WeGo_FrontEnd/WeGo_FrontEnd/src/api/service/user-service/index.ts 73.33% (+0.83%) ⬆️
/home/runner/work/WeGo_FrontEnd/WeGo_FrontEnd/src/hooks/use-user/use-user-get-me/index.ts 100.00% (+13.52%) ⬆️

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 21, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/app/message/chat/[roomId]/page.tsx (1)

12-19: ⚠️ Potential issue | 🟡 Minor

me?.userId 의 불필요한 옵셔널 체이닝이 userId: undefined 를 하위에 전달할 수 있음

getMe()는 인증 실패 시 예외를 던지므로, 실행이 Line 13에 도달했을 때 me는 항상 유효한 User 객체입니다. 따라서 me?.userId는 불필요하며, 타입을 number | undefined로 넓혀 ChatRoomPageuserId prop이 number를 기대하는 경우 TypeScript 타입 불일치를 유발합니다. 최악의 경우 userId={undefined}로 렌더링되어 채팅 룸 로직이 깨질 수 있습니다.

🛡️ 수정 제안
-  const me = await API.userService.getMe();
-  const userId = me?.userId;
+  const me = await API.userService.getMe();
+  const userId = me.userId;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app/message/chat/`[roomId]/page.tsx around lines 12 - 19, Remove the
unnecessary optional chaining on me when passing userId to ChatRoomPage: since
API.userService.getMe() throws on auth failure, me is guaranteed to be a User at
the point after await API.userService.getMe(), so replace me?.userId with
me.userId and ensure the prop type matches (ChatRoomPage userId expects number);
update any surrounding null/undefined handling if needed so userId is a number
when calling ChatRoomPage (refer to getMe(), me, userId, and ChatRoomPage in
this file).
src/hooks/use-user/use-user-get/index.ts (1)

7-18: ⚠️ Potential issue | 🟠 Major

useSuspenseQueryenabled 옵션을 지원하지 않으므로 options 파라미터 시그니처가 부정확함

useSuspenseQuery는 TanStack Query v5에서 enabled 옵션을 명시적으로 제외합니다. 현재 훅이 options?: { enabled?: boolean }을 수용하고 ...options로 스프레드하면, 호출 측에서 enabled: false를 전달했을 때 런타임에서 묵묵히 무시되어 쿼리가 항상 실행됩니다.

현재 코드에서는 useGetUser({ userId })로 호출되며 누구도 enabled 옵션을 전달하지 않지만, 훅 시그니처가 enabled를 허용하도록 되어 있어 향후 호출 측에서 오용할 가능성이 있습니다. TypeScript도 변수 스프레드(...options)에 대해서는 여분의 프로퍼티를 타입 에러로 잡지 않으므로 컴파일 단계에서 감지되지 않습니다.

♻️ 수정 예시 (options 파라미터 제거)
-export const useGetUser = ({ userId }: GetUserPathParams, options?: { enabled?: boolean }) => {
+export const useGetUser = ({ userId }: GetUserPathParams) => {
   const query = useSuspenseQuery({
     queryKey: userKeys.item(userId),
     queryFn: () => API.userService.getUser({ userId }),
-    ...options,
     select: (data) => ({
       ...data,
       profileImage: data.profileImage ?? '',
       profileMessage: data.profileMessage ?? '',
       mbti: data.mbti ?? '',
     }),
   });
   return query;
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/hooks/use-user/use-user-get/index.ts` around lines 7 - 18, The hook
useGetUser declares an options parameter that includes enabled, but
useSuspenseQuery does not support enabled; remove the options parameter (and the
spread ...options) from useGetUser to avoid suggesting callers can pass enabled,
or alternatively replace it with a properly typed options object that excludes
enabled; update the useGetUser implementation (the call to useSuspenseQuery and
its signature) so it no longer accepts or spreads an options that may contain
enabled, keeping the select mapping and other logic intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/app/message/page.tsx`:
- Around line 26-27: Replace optional chaining on the current user ID so the
prop types align: where you call API.userService.getMe() (function getMe) and
currently use me?.userId, change it to me.userId; update the usage passed into
ChatRoomPage (prop userId: number) so it receives a definite number, not number
| undefined, ensuring the variable from getMe() (me.userId) is used consistently
across chat/[roomId]/page.tsx and src/app/message/page.tsx.

---

Outside diff comments:
In `@src/app/message/chat/`[roomId]/page.tsx:
- Around line 12-19: Remove the unnecessary optional chaining on me when passing
userId to ChatRoomPage: since API.userService.getMe() throws on auth failure, me
is guaranteed to be a User at the point after await API.userService.getMe(), so
replace me?.userId with me.userId and ensure the prop type matches (ChatRoomPage
userId expects number); update any surrounding null/undefined handling if needed
so userId is a number when calling ChatRoomPage (refer to getMe(), me, userId,
and ChatRoomPage in this file).

In `@src/hooks/use-user/use-user-get/index.ts`:
- Around line 7-18: The hook useGetUser declares an options parameter that
includes enabled, but useSuspenseQuery does not support enabled; remove the
options parameter (and the spread ...options) from useGetUser to avoid
suggesting callers can pass enabled, or alternatively replace it with a properly
typed options object that excludes enabled; update the useGetUser implementation
(the call to useSuspenseQuery and its signature) so it no longer accepts or
spreads an options that may contain enabled, keeping the select mapping and
other logic intact.

@Chiman2937 Chiman2937 changed the title [Refactor] 프로필 페이지 로직 간소화 [Refactor] 프로필 페이지 Redirect 로직 간소화 Feb 22, 2026
@Chiman2937 Chiman2937 merged commit 6cab0f4 into main Feb 22, 2026
9 checks passed
@Chiman2937 Chiman2937 deleted the chiyoung-refactor/profile-page branch February 22, 2026 06:13
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