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: useAuth 중복수정 #90

Merged
merged 5 commits into from
Jan 1, 2025
Merged

feat: useAuth 중복수정 #90

merged 5 commits into from
Jan 1, 2025

Conversation

Han-wo
Copy link
Collaborator

@Han-wo Han-wo commented Dec 27, 2024

#️⃣ 이슈

📝 작업 내용

인증인가 부분 최적화입니다
이전에는 init 초기화되는 중에 컴포넌트가 랜더링되면 계속해서 초기화가 됐는데 이제는 하나를 초기화하고 있으면 그걸 이어서 하는걸로 수정했습니다.

이제 인증이 필요한 컴포넌트에서만 useAuth를 호출합니다

📸 스크린샷

이전
useAuth 최적화 이전

이후
최적화 후

✅ 체크 리스트

  • 적절한 Title 작성
  • 적절한 Label 지정
  • Assignee 및 Reviewer 지정
  • 로컬 작동 확인
  • Merge 되는 브랜치 확인

👩‍💻 공유 포인트 및 논의 사항

Summary by CodeRabbit

  • 새로운 기능
    • 인증 상태 초기화를 추적하는 isInitializing 속성이 추가되었습니다.
    • 인증 성공 시 isAuthenticated가 항상 true로 설정됩니다.
    • 초기화 중 중복 실행 방지를 위한 프로미스 캐싱 기능이 추가되었습니다.
    • 서비스가 사용 불가능할 때 사용자에게 친숙한 메시지를 표시하는 NotFound 컴포넌트가 추가되었습니다.
  • 버그 수정
    • 초기화 중 오류 발생 시 상태 업데이트가 개선되었습니다.
  • 문서화
    • 메서드 기능에 대한 설명이 추가되었습니다.

@Han-wo Han-wo added 우선순위: MEDIUM New feature or request ✨ FEAT This doesn't seem right labels Dec 27, 2024
@Han-wo Han-wo requested a review from cindycho0423 December 27, 2024 09:02
@Han-wo Han-wo self-assigned this Dec 27, 2024
@Han-wo Han-wo linked an issue Dec 27, 2024 that may be closed by this pull request
1 task
Copy link

coderabbitai bot commented Dec 27, 2024

Walkthrough

src/hooks/use-auth.ts 파일의 Zustand 인증 스토어에 대한 최적화 작업이 수행되었습니다. isInitializing 부울 속성을 추가하여 초기화 상태를 추적하고, initAuth 메서드의 초기화 로직을 개선했습니다. 중복 초기화를 방지하기 위해 프로미스 캐싱 메커니즘을 도입하고, 오류 처리를 강화했습니다. setAuthclearAuth 메서드는 쿠키 설정과 삭제를 병렬로 처리하도록 업데이트되었습니다. 또한, src/app/error.tsx 파일에 사용자 친화적인 메시지를 표시하는 NotFound 컴포넌트가 추가되었습니다.

Changes

파일 변경 내용
src/hooks/use-auth.ts - isInitializing 속성 추가
- create 함수에 get 매개변수 도입
- setAuth 메서드 로직 업데이트
- clearAuth 메서드 로직 업데이트
- initAuth 메서드 리팩토링 및 초기화 로직 최적화
src/app/error.tsx - 새로운 컴포넌트 NotFound 추가

Assessment against linked issues

목표 해결 여부 설명
사용자 인증인가 최적화 [#88]

Possibly related PRs

Poem

🐰 토끼의 인증 마법
초기화의 춤을 추는 훅
프로미스 캐시로 최적화
인증의 문을 활짝 열어
안전하고 빠른 로그인 여정 🔐


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

github-actions bot commented Dec 27, 2024

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

🔭 Outside diff range comments (1)
src/hooks/use-auth.ts (1)

Line range hint 115-141: 쿠키 설정 작업의 최적화 및 에러 처리 필요

현재 구현은 각 쿠키를 개별적으로 설정하고 있으며, 에러 처리가 누락되어 있습니다. 또한 쿠키 설정 실패 시 상태 업데이트가 일관성 없이 진행될 수 있습니다.

다음과 같은 개선사항을 제안드립니다:

  1. 쿠키 설정을 일괄 처리하는 유틸리티 함수 도입
  2. try-catch 블록을 통한 에러 처리 추가
  3. 트랜잭션적 접근을 통한 일관성 보장
setAuth: async (response: LoginResponse) => {
+ try {
    const {
      token,
      memberId,
      memberName,
      memberNickName,
      annualIncome,
      deposit,
    } = response;

-   await setCookie("token", token);
-   await setCookie("memberId", memberId.toString());
-   await setCookie("memberName", memberName);
-   await setCookie("memberNickName", memberNickName);
-   await setCookie("annualIncome", annualIncome.toString());
-   await setCookie("deposit", deposit.toString());
+   await Promise.all([
+     setCookie("token", token),
+     setCookie("memberId", memberId.toString()),
+     setCookie("memberName", memberName),
+     setCookie("memberNickName", memberNickName),
+     setCookie("annualIncome", annualIncome.toString()),
+     setCookie("deposit", deposit.toString())
+   ]);

    set({
      token,
      memberId,
      memberName,
      memberNickName,
      annualIncome,
      deposit,
      isAuthenticated: true,
      isInitialized: true,
    });
+ } catch (error) {
+   console.error('인증 정보 설정 중 오류 발생:', error);
+   throw error;
+ }
🧹 Nitpick comments (3)
src/hooks/use-auth.ts (3)

25-25: isInitializing 상태에 대한 문서화 필요

새로 추가된 isInitializing 상태 필드에 대한 설명이 인터페이스에 누락되어 있습니다. 다른 개발자들의 이해를 돕기 위해 JSDoc 문서화가 필요합니다.

다음과 같이 문서화를 추가해주세요:

interface AuthStore {
+ /** 인증 초기화가 진행 중인지 여부를 나타내는 플래그 */
  isInitializing: boolean;

90-91: Promise 변수의 타입 안전성 개선 필요

initPromise 변수가 명시적인 타입 선언 없이 초기화되었습니다. 타입 안전성을 위해 명시적인 타입 선언을 추가하는 것이 좋습니다.

다음과 같이 수정해주세요:

- let initPromise: Promise<void> | null = null;
+ const initPromise = {
+   current: null as Promise<void> | null
+ };

185-234: 초기화 로직의 견고성 향상

전반적으로 잘 구현되어 있으나, 몇 가지 개선 포인트가 있습니다:

  1. 숫자 파싱 시 발생할 수 있는 예외 처리
  2. 초기화 실패 시의 상태 처리 개선

다음과 같은 개선사항을 제안드립니다:

try {
  set({ isInitializing: true });

  const token = await getCookie("token");
  const memberIdStr = await getCookie("memberId");
  const memberName = await getCookie("memberName");
  const memberNickName = await getCookie("memberNickName");
  const annualIncomeStr = await getCookie("annualIncome");
  const depositStr = await getCookie("deposit");

- const memberId = memberIdStr ? parseInt(memberIdStr, 10) : null;
- const annualIncome = annualIncomeStr
-   ? parseInt(annualIncomeStr, 10)
-   : null;
- const deposit = depositStr ? parseInt(depositStr, 10) : null;
+ const memberId = memberIdStr ? Number(memberIdStr) || null : null;
+ const annualIncome = annualIncomeStr ? Number(annualIncomeStr) || null : null;
+ const deposit = depositStr ? Number(depositStr) || null : null;

  set({
    token,
    memberId,
    memberName,
    memberNickName,
    annualIncome,
    deposit,
    isAuthenticated: !!token,
    isInitialized: true,
    isInitializing: false,
  });
} catch (error) {
  set({
    isInitialized: true,
    isInitializing: false,
+   isAuthenticated: false,
+   token: null,
+   memberId: null,
+   memberName: null,
+   memberNickName: null,
+   annualIncome: null,
+   deposit: null
  });
  throw error;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 004a54c and ccfa261.

📒 Files selected for processing (1)
  • src/hooks/use-auth.ts (3 hunks)

Comment on lines 154 to 171
clearAuth: async () => {
await deleteCookie("token");
await deleteCookie("memberId");
await deleteCookie("memberName");
await deleteCookie("memberNickName");
await deleteCookie("annualIncome");
await deleteCookie("deposit");

set({
token: null,
memberId: null,
memberName: null,
memberNickName: null,
annualIncome: null,
deposit: null,
isAuthenticated: false,
isInitialized: true,
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

로그아웃 처리의 안정성 개선 필요

setAuth와 동일한 패턴의 문제가 있습니다. 쿠키 삭제 작업의 최적화와 에러 처리가 필요합니다.

다음과 같이 개선해주세요:

clearAuth: async () => {
+ try {
-   await deleteCookie("token");
-   await deleteCookie("memberId");
-   await deleteCookie("memberName");
-   await deleteCookie("memberNickName");
-   await deleteCookie("annualIncome");
-   await deleteCookie("deposit");
+   await Promise.all([
+     deleteCookie("token"),
+     deleteCookie("memberId"),
+     deleteCookie("memberName"),
+     deleteCookie("memberNickName"),
+     deleteCookie("annualIncome"),
+     deleteCookie("deposit")
+   ]);

    set({
      token: null,
      memberId: null,
      memberName: null,
      memberNickName: null,
      annualIncome: null,
      deposit: null,
      isAuthenticated: false,
      isInitialized: true,
    });
+ } catch (error) {
+   console.error('로그아웃 처리 중 오류 발생:', error);
+   throw error;
+ }
📝 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
clearAuth: async () => {
await deleteCookie("token");
await deleteCookie("memberId");
await deleteCookie("memberName");
await deleteCookie("memberNickName");
await deleteCookie("annualIncome");
await deleteCookie("deposit");
set({
token: null,
memberId: null,
memberName: null,
memberNickName: null,
annualIncome: null,
deposit: null,
isAuthenticated: false,
isInitialized: true,
});
clearAuth: async () => {
try {
await Promise.all([
deleteCookie("token"),
deleteCookie("memberId"),
deleteCookie("memberName"),
deleteCookie("memberNickName"),
deleteCookie("annualIncome"),
deleteCookie("deposit")
]);
set({
token: null,
memberId: null,
memberName: null,
memberNickName: null,
annualIncome: null,
deposit: null,
isAuthenticated: false,
isInitialized: true,
});
} catch (error) {
console.error('로그아웃 처리 중 오류 발생:', error);
throw error;
}

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

🔭 Outside diff range comments (1)
src/hooks/use-auth.ts (1)

Line range hint 104-134: 에러 처리 로직 추가가 필요합니다

쿠키 설정 작업 중 발생할 수 있는 오류에 대한 처리가 없습니다.

다음과 같이 try-catch 블록을 추가하는 것을 추천드립니다:

 setAuth: async (response: LoginResponse) => {
+  try {
     const {
       token,
       memberId,
       memberName,
       memberNickName,
       annualIncome,
       deposit,
     } = response;

     await Promise.all([
       setCookie("token", token),
       setCookie("memberId", memberId.toString()),
       setCookie("memberName", memberName),
       setCookie("memberNickName", memberNickName),
       setCookie("annualIncome", annualIncome.toString()),
       setCookie("deposit", deposit.toString()),
     ]);

     set({
       token,
       memberId,
       memberName,
       memberNickName,
       annualIncome,
       deposit,
       isAuthenticated: true,
       isInitialized: true,
     });
+  } catch (error) {
+    console.error('인증 정보 설정 중 오류 발생:', error);
+    throw error;
+  }
 },
🧹 Nitpick comments (2)
src/hooks/use-auth.ts (2)

90-102: 타입 안전성 개선이 필요합니다

initPromise 변수의 타입 안전성을 높일 수 있습니다.

다음과 같이 개선해보세요:

- let initPromise: Promise<void> | null = null;
+ let initPromise: Promise<void> | null | undefined = null;

또한 초기 상태를 별도의 상수로 분리하면 코드의 가독성과 재사용성이 향상될 것 같습니다:

const initialState = {
  token: null,
  memberId: null,
  memberName: null,
  memberNickName: null,
  annualIncome: null,
  deposit: null,
  isAuthenticated: false,
  isInitialized: false,
  isInitializing: false,
} as const;

159-218: 메모리 누수 방지를 위한 정리(cleanup) 로직 추가 필요

컴포넌트가 언마운트되거나 초기화가 중단되었을 때 initPromise를 정리하는 메커니즘이 없습니다.

다음과 같은 cleanup 함수를 추가하는 것을 고려해보세요:

const cleanup = () => {
  initPromise = null;
};

// useAuth 훅을 사용하는 컴포넌트에서:
useEffect(() => {
  initAuth();
  return cleanup;
}, []);

또한 초기화 상태 변경을 추적할 수 있도록 디버그 로그를 추가하는 것도 좋을 것 같습니다:

 try {
+  console.debug('인증 초기화 시작');
   set({ isInitializing: true });
   // ... existing code ...
   set({
     // ... existing code ...
   });
+  console.debug('인증 초기화 완료');
 } catch (error) {
+  console.error('인증 초기화 실패:', error);
   set({
     isInitialized: true,
     isInitializing: false,
   });
   throw error;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ccfa261 and 1ae3765.

📒 Files selected for processing (1)
  • src/hooks/use-auth.ts (3 hunks)
🔇 Additional comments (2)
src/hooks/use-auth.ts (2)

32-77: 문서화가 잘 되어있습니다! 👍

JSDoc 문서화가 매우 상세하고 실용적입니다. 특히 다음 사항들이 인상적입니다:

  • 명확한 사용 사례와 예제 코드 제공
  • 각 시나리오별 구현 방법 설명
  • 컴포넌트 수준의 실제 사용 예시

136-157: 이전 리뷰 제안사항이 잘 반영되었습니다

쿠키 삭제 작업을 Promise.all을 사용하여 병렬로 처리하도록 개선한 것이 좋습니다.

@Han-wo Han-wo merged commit de9b924 into develop Jan 1, 2025
4 of 5 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: 0

🧹 Nitpick comments (2)
src/app/error.tsx (2)

5-6: 함수 이름 개선을 고려해보세요.

현재 NotFound라는 이름은 404 에러 페이지를 연상시키지만, 실제로는 서비스 점검 안내를 제공하고 있습니다. 페이지 목적에 맞춰 ServiceMaintenance 등 더 의도가 명확한 이름을 사용하면 가독성과 유지보수성이 높아집니다.


7-20: 추가적인 안내 요소를 고려해보세요.

사용자가 기다리는 동안 다른 페이지로 이동하거나, 홈 화면으로 돌아갈 수 있도록 링크 혹은 버튼을 제공하면 UX가 개선됩니다.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ae3765 and e56cbd0.

📒 Files selected for processing (1)
  • src/app/error.tsx (1 hunks)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
✨ FEAT This doesn't seem right 우선순위: MEDIUM New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

feat: 사용자 인증인가 최적화
1 participant