Feat/axios interceptor#13
Conversation
Summary of ChangesHello @dasosann, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! 이 PR은 Axios와 React Query를 활용하여 프로젝트의 API 통신 계층을 구축합니다. 클라이언트 측과 서버 측 요청을 위한 명확하게 분리된 API 인스턴스를 제공하며, 특히 서버 측 요청 시 쿠키 처리를 자동화하여 데이터 관리의 효율성과 일관성을 높입니다. 이는 향후 애플리케이션의 데이터 페칭 및 상태 관리 기반을 마련합니다. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
|
@gemini-code-assist 다시 리뷰해줘 |
There was a problem hiding this comment.
Code Review
Axios 인터셉터를 활용하여 클라이언트와 서버 환경에 맞는 API 클라이언트를 구현하신 점이 좋습니다. 특히 서버 환경에서 next/headers의 cookies()를 사용하여 인증 정보를 전달하는 로직이 인상적입니다. 코드의 재사용성과 보안을 더욱 향상시키기 위해 몇 가지 제안 사항을 남깁니다. 서버 전용 환경 변수 사용, 쿠키 전달 방식 개선, API 클라이언트의 역할 분리 등을 고려해보시면 좋겠습니다. 또한, 코드 중복을 줄여 유지보수성을 높이는 리팩터링도 제안 드립니다.
| const cookieStore = await cookies(); | ||
| const allCookies = cookieStore.toString(); // "key=value; key2=value2" 형태 | ||
|
|
||
| if (allCookies) { | ||
| config.headers.Cookie = allCookies; | ||
| } |
There was a problem hiding this comment.
cookieStore.toString()을 사용하여 모든 쿠키를 API 요청 헤더에 그대로 전달하는 방식은 보안 및 성능상 잠재적인 위험을 가집니다.
이 방식은 API 인증과 무관한 제3자 서비스(예: 분석 도구)의 쿠키까지 백엔드 서버로 전송하여 불필요한 데이터를 노출할 수 있으며, 헤더 크기 제한을 초과할 위험도 있습니다.
필요한 세션 또는 인증 토큰 쿠키(예: accessToken)만 선별하여 전달하는 방식으로 리팩터링하는 것을 강력히 권장합니다.
| const cookieStore = await cookies(); | |
| const allCookies = cookieStore.toString(); // "key=value; key2=value2" 형태 | |
| if (allCookies) { | |
| config.headers.Cookie = allCookies; | |
| } | |
| const cookieStore = await cookies(); | |
| const sessionCookie = cookieStore.get("session-token"); // 예시: 실제 사용하는 인증 쿠키 이름으로 변경하세요. | |
| if (sessionCookie) { | |
| config.headers.Cookie = `${sessionCookie.name}=${sessionCookie.value}`; | |
| } |
| }); | ||
|
|
||
| // 에러를 던져서 상위 컴포넌트나 Error Boundary가 처리하게 함 | ||
| throw new Error(errorMessage); |
There was a problem hiding this comment.
throw new Error(errorMessage)로 새로운 에러를 생성하여 던지면, 원래 axios 에러가 가지고 있던 상태 코드(status)나 다른 유용한 컨텍스트 정보가 손실됩니다.
에러를 처리하는 상위 컴포넌트(error.tsx 등)에서 상태 코드에 따라 다른 UI를 보여주기 어려워집니다.
console.error로 이미 상세 정보를 로깅하고 있으므로, 여기서는 원본 error 객체를 그대로 다시 던져 호출자가 전체 컨텍스트를 활용할 수 있도록 하는 것이 좋습니다.
| throw new Error(errorMessage); | |
| throw error; |
|
@gemini-code-assist review |
|
/describe |
|
PR Description updated to latest commit (627c954)
|
There was a problem hiding this comment.
File Walkthrough
Enhancement
| ||
Dependencies
|
There was a problem hiding this comment.
Code Review
이번 PR은 Axios 인스턴스 및 서버 API 클라이언트 구현, 그리고 TanStack Query 의존성 추가를 통해 API 통신 및 상태 관리의 기반을 마련했습니다. 클라이언트와 서버 환경에 맞는 Axios 설정을 분리하고, 인증 토큰 재발급 로직을 인터셉터로 처리한 점은 매우 긍정적입니다. 전반적으로 잘 구성된 PR이지만, 몇 가지 개선 사항을 제안합니다. 특히 하드코딩된 문자열을 상수로 분리하고, 타입 안정성을 높이는 방향으로 코드를 개선하면 유지보수성과 견고성을 더욱 향상시킬 수 있습니다.
| if ( | ||
| error.response?.status === 401 && | ||
| !originalRequest._retry && | ||
| originalRequest.url !== "/api/auth/login" |
| console.error(`[Server API Error] ${method} ${path}`, { | ||
| status, | ||
| message: errorMessage, | ||
| data: error.response?.data, | ||
| }); |
There was a problem hiding this comment.
console.error를 사용하여 에러를 로깅하는 것은 개발 환경에서는 유용하지만, 프로덕션 환경에서는 Sentry와 같은 중앙 집중식 로깅/에러 모니터링 솔루션을 사용하는 것이 더 효과적입니다. 현재 구현은 기능적으로 문제가 없으나, 향후 운영을 위해 고려해볼 사항입니다.
| console.error(`[Server API Error] ${method} ${path}`, { | |
| status, | |
| message: errorMessage, | |
| data: error.response?.data, | |
| }); | |
| // 프로덕션 환경에서는 Sentry 등 중앙 집중식 로깅 솔루션 사용을 고려 | |
| console.error(`[Server API Error] ${method} ${path}`, { | |
| status, | |
| message: errorMessage, | |
| data: error.response?.data, | |
| }); |
PR Type
Enhancement
Description
Axios 인스턴스와 인터셉터 구현으로 API 요청 관리 체계화
클라이언트/서버 환경 분리 및 401 토큰 자동 재발급 처리
TanStack Query 및 개발 도구 의존성 추가
서버 환경에서 쿠키 기반 인증 처리 로직 구현
Diagram Walkthrough
File Walkthrough
axios.ts
클라이언트용 Axios 인스턴스 및 토큰 재발급 인터셉터lib/axios.ts
_retry)로 무한 루프 방지server-api.ts
서버 환경 API 클라이언트 및 쿠키 기반 인증lib/server-api.ts
request()함수와 HTTP 메서드별 래퍼 함수(get,post,put,delete,patch) 제공package.json
API 관리 및 개발 도구 의존성 추가package.json
@tanstack/react-query^5.90.20 추가@tanstack/react-query-devtools^5.91.2 추가axios^1.13.3 추가pnpm-lock.yaml
의존성 잠금 파일 업데이트pnpm-lock.yaml
react-query-devtools)
mime-db)
✨ Describe tool usage guide:
Overview:
The
describetool scans the PR code changes, and generates a description for the PR - title, type, summary, walkthrough and labels. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.When commenting, to edit configurations related to the describe tool (
pr_descriptionsection), use the following template:With a configuration file, use the following template:
Enabling\disabling automation
meaning the
describetool will run automatically on every PR.the tool will replace every marker of the form
pr_agent:marker_namein the PR description with the relevant content, wheremarker_nameis one of the following:type: the PR type.summary: the PR summary.walkthrough: the PR walkthrough.diagram: the PR sequence diagram (if enabled).Note that when markers are enabled, if the original PR description does not contain any markers, the tool will not alter the description at all.
Custom labels
The default labels of the
describetool are quite generic: [Bug fix,Tests,Enhancement,Documentation,Other].If you specify custom labels in the repo's labels page or via configuration file, you can get tailored labels for your use cases.
Examples for custom labels:
Main topic:performance- pr_agent:The main topic of this PR is performanceNew endpoint- pr_agent:A new endpoint was added in this PRSQL query- pr_agent:A new SQL query was added in this PRDockerfile changes- pr_agent:The PR contains changes in the DockerfileThe list above is eclectic, and aims to give an idea of different possibilities. Define custom labels that are relevant for your repo and use cases.
Note that Labels are not mutually exclusive, so you can add multiple label categories.
Make sure to provide proper title, and a detailed and well-phrased description for each label, so the tool will know when to suggest it.
Inline File Walkthrough 💎
For enhanced user experience, the
describetool can add file summaries directly to the "Files changed" tab in the PR page.This will enable you to quickly understand the changes in each file, while reviewing the code changes (diffs).
To enable inline file summary, set
pr_description.inline_file_summaryin the configuration file, possible values are:'table': File changes walkthrough table will be displayed on the top of the "Files changed" tab, in addition to the "Conversation" tab.true: A collapsable file comment with changes title and a changes summary for each file in the PR.false(default): File changes walkthrough will be added only to the "Conversation" tab.Utilizing extra instructions
The
describetool can be configured with extra instructions, to guide the model to a feedback tailored to the needs of your project.Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Notice that the general structure of the description is fixed, and cannot be changed. Extra instructions can change the content or style of each sub-section of the PR description.
Examples for extra instructions:
Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.
More PR-Agent commands
See the describe usage page for a comprehensive guide on using this tool.