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! This pull request establishes a foundational layer for API communication by integrating Axios and Tanstack Query. It provides a dedicated client-side Axios instance for general requests and a specialized server-side utility to ensure proper cookie forwarding, which is crucial for authenticated server-rendered pages. This setup aims to streamline data fetching and management across the application's client and server environments. 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
|
There was a problem hiding this comment.
Code Review
Axios 인스턴스와 서버/클라이언트 API 요청 구조를 추가하고, React Query 관련 의존성을 설치하는 PR입니다. 전반적으로 좋은 방향이지만, 몇 가지 개선점을 제안합니다. server-api.ts의 경우 현재 GET 요청만 처리 가능하여 확장성이 부족하므로, POST, PUT 등 다른 HTTP 메소드도 지원하는 범용적인 구조로 리팩토링하는 것이 좋습니다. 또한, package.json에 명시된 axios 버전이 공식적으로 존재하지 않는 버전으로 보여, 보안 및 안정성을 위해 최신 안정 버전으로 업데이트하는 것을 권장하며, 이러한 공유 설정 파일 변경은 팀과 논의가 필요합니다. 자세한 내용은 각 파일의 리뷰 코멘트를 참고해주세요.
| import { cookies } from "next/headers"; | ||
| import { api } from "./axios"; | ||
| import type { AxiosRequestConfig } from "axios"; | ||
|
|
||
| export async function serverApi(url: string, options: AxiosRequestConfig = {}) { | ||
| const cookieStore = await cookies(); | ||
|
|
||
| // 기존 api 인스턴스를 쓰되, 쿠키 헤더만 쓱 끼워넣기 | ||
| return api.get(url, { | ||
| ...options, | ||
| headers: { | ||
| ...options.headers, // 기존 헤더 유지 | ||
| Cookie: cookieStore.toString(), // 쿠키 추가 | ||
| }, | ||
| }); | ||
| } |
There was a problem hiding this comment.
현재 serverApi 함수는 GET 요청에만 사용 가능하도록 하드코딩되어 있습니다. 이는 향후 POST, PUT, DELETE 등 다른 HTTP 메소드를 사용해야 할 때 코드 중복을 유발하고 확장성을 저해할 수 있습니다. 보다 일반적이고 재사용 가능한 구조로 리팩토링하는 것을 강력히 권장합니다. 예를 들어, serverApi를 각 HTTP 메소드를 지원하는 함수를 가진 객체로 만들면 API의 일관성을 유지하고, 새로운 HTTP 메소드가 필요할 때 쉽게 확장할 수 있습니다.
import { cookies } from "next/headers";
import { api } from "./axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
// 서버 환경에서 사용할 API 클라이언트입니다.
// next/headers의 cookies()를 사용하여 요청에 자동으로 쿠키를 포함시킵니다.
async function request<T>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
const cookieStore = await cookies();
const cookieHeader = cookieStore.toString();
return api({
...config,
headers: {
...config.headers,
...(cookieHeader && { Cookie: cookieHeader }),
},
});
}
export const serverApi = {
get: <T = any>(url: string, config?: AxiosRequestConfig) =>
request<T>({ ...config, method: "GET", url }),
post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
request<T>({ ...config, method: "POST", url, data }),
put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
request<T>({ ...config, method: "PUT", url, data }),
delete: <T = any>(url: string, config?: AxiosRequestConfig) =>
request<T>({ ...config, method: "DELETE", url }),
patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
request<T>({ ...config, method: "PATCH", url, data }),
};References
- 함수 이름이 의미론적이어야 하며(52), 코드 중복을 피하기 위해 재사용 가능한 유틸리티로 추출해야 합니다(54). 현재
serverApi는 GET만 지원하여 이름이 오해의 소지가 있고, 다른 메소드 추가 시 코드 중복이 발생할 수 있습니다. (link)
|
@gemini-code-assist review |
|
/describe |
|
@gemini-code-assist 다시 리뷰해줘 |
|
PR Description updated to latest commit (f3d8e71)
|
There was a problem hiding this comment.
File Walkthrough
Enhancement
| ||
Dependencies
|
There was a problem hiding this comment.
Code Review
안녕하세요. Axios 인터셉터 및 API 클라이언트 구조 개선을 위한 PR 잘 보았습니다. 클라이언트와 서버 환경을 분리하여 API 요청을 처리하는 구조를 도입하고, TanStack React Query를 추가하여 데이터 페칭의 기반을 마련한 점이 인상적입니다. 코드 리뷰 결과, 서버 API에서 쿠키를 처리하는 방식에 치명적인 오류가 발견되었으며, 타입스크립트 타입을 개선하여 안정성과 개발 경험을 높일 수 있는 몇 가지 사항을 제안드립니다. 자세한 내용은 각 파일의 주석을 참고해주세요.
| const cookieStore = await cookies(); | ||
| const cookieHeader = cookieStore.toString(); |
There was a problem hiding this comment.
안녕하세요. cookies()에서 반환된 cookieStore 객체에 toString() 메서드를 사용하는 것은 쿠키 문자열을 직렬화하는 안정적인 방법이 아닙니다. ReadonlyRequestCookies 타입에는 toString()이 공식적으로 정의되어 있지 않아 예상치 못한 동작이나 오류를 발생시킬 수 있습니다.
cookieStore.getAll()을 사용하여 모든 쿠키를 배열로 가져온 후, 이를 key=value 형태의 문자열로 조합하여 Cookie 헤더를 생성하는 것이 올바른 방법입니다. 아래 제안 코드를 참고하여 수정하시는 것을 권장합니다.
const cookieStore = await cookies();
const cookieHeader = cookieStore
.getAll()
.map((cookie) => `${cookie.name}=${cookie.value}`)
.join("; ");| post: <T = unknown>( | ||
| url: string, | ||
| data?: unknown, | ||
| config?: AxiosRequestConfig, | ||
| ) => request<T>({ ...config, method: "POST", url, data }), |
There was a problem hiding this comment.
타입 안정성 및 개발자 경험 향상을 위해 post 메서드의 data 파라미터 타입을 unknown 대신 제네릭 D로 지정하는 것을 제안합니다. 이렇게 하면 serverApi.post를 호출하는 쪽에서 요청 본문의 타입을 명시할 수 있어 타입 추론이 더 원활해지고 코드의 안정성이 높아집니다. 이는 레포지토리 스타일 가이드에서 강조하는 타입 안정성 원칙과도 부합합니다. put, patch 메서드에도 동일하게 적용할 수 있습니다.
post: <T = unknown, D = unknown>(
url: string,
data?: D,
config?: AxiosRequestConfig,
) => request<T>({ ...config, method: "POST", url, data }),| put: <T = unknown>( | ||
| url: string, | ||
| data?: unknown, | ||
| config?: AxiosRequestConfig, | ||
| ) => request<T>({ ...config, method: "PUT", url, data }), |
There was a problem hiding this comment.
타입 안정성 및 개발자 경험 향상을 위해 put 메서드의 data 파라미터 타입을 unknown 대신 제네릭 D로 지정하는 것을 제안합니다. 이렇게 하면 serverApi.put을 호출하는 쪽에서 요청 본문의 타입을 명시할 수 있어 타입 추론이 더 원활해지고 코드의 안정성이 높아집니다. 이는 레포지토리 스타일 가이드에서 강조하는 타입 안정성 원칙과도 부합합니다.
put: <T = unknown, D = unknown>(
url: string,
data?: D,
config?: AxiosRequestConfig,
) => request<T>({ ...config, method: "PUT", url, data }),| patch: <T = unknown>( | ||
| url: string, | ||
| data?: unknown, | ||
| config?: AxiosRequestConfig, | ||
| ) => request<T>({ ...config, method: "PATCH", url, data }), |
There was a problem hiding this comment.
타입 안정성 및 개발자 경험 향상을 위해 patch 메서드의 data 파라미터 타입을 unknown 대신 제네릭 D로 지정하는 것을 제안합니다. 이렇게 하면 serverApi.patch를 호출하는 쪽에서 요청 본문의 타입을 명시할 수 있어 타입 추론이 더 원활해지고 코드의 안정성이 높아집니다. 이는 레포지토리 스타일 가이드에서 강조하는 타입 안정성 원칙과도 부합합니다.
patch: <T = unknown, D = unknown>(
url: string,
data?: D,
config?: AxiosRequestConfig,
) => request<T>({ ...config, method: "PATCH", url, data }),There was a problem hiding this comment.
Code Review
이번 PR은 Axios 인스턴스 및 서버 API 클라이언트를 구현하고, React Query 및 개발자 도구 의존성을 추가하여 클라이언트/서버 환경 분리 요청 처리를 지원하는 중요한 개선 사항입니다. 특히 lib/axios.ts와 lib/server-api.ts로 클라이언트와 서버 환경의 API 호출을 명확히 분리한 점은 코드 구성 측면에서 매우 긍정적입니다. Next.js 15+의 await cookies() 사용과 제네릭 타입을 통한 응답 타입 안정성 확보도 잘 이루어졌습니다. 전반적으로 코드 품질과 유지보수성을 높이는 좋은 변경입니다.
| @@ -0,0 +1,46 @@ | |||
| import { cookies } from "next/headers"; | |||
There was a problem hiding this comment.
cookies() 함수는 Next.js의 Server Components 또는 Server Actions에서만 호출되어야 합니다. 현재 lib/server-api.ts 파일은 서버 환경에서만 사용될 것으로 예상되지만, 실수로 클라이언트 컴포넌트에서 이 파일을 import 하여 request 함수를 호출할 경우 런타임 에러가 발생할 수 있습니다. 이를 방지하고 파일의 의도를 명확히 하기 위해 파일 상단에 'use server' 지시어를 추가하여 해당 파일이 Server Action으로 동작하도록 명시하는 것을 권장합니다. 이는 빌드 시점에 잠재적인 문제를 감지하는 데 도움이 됩니다.
| import { cookies } from "next/headers"; | |
| 'use server'; | |
| import { cookies } from "next/headers"; |
| const axiosConfig = { | ||
| baseURL: process.env.NEXT_PUBLIC_API_URL, | ||
| headers: { "Content-Type": "application/json" }, | ||
| withCredentials: true, |
There was a problem hiding this comment.
클라이언트 환경에서 withCredentials: true 설정은 브라우저가 자동으로 쿠키를 포함하도록 하여 유용합니다. 하지만 이 axiosConfig를 사용하여 생성된 api 인스턴스가 lib/server-api.ts에서 서버 환경 요청에도 재사용되고 있습니다. 서버 환경에서는 withCredentials 설정이 무의미하며, next/headers의 cookies()를 통해 쿠키를 수동으로 주입하는 방식이 올바릅니다. 코드의 의도를 더욱 명확히 하고 잠재적인 혼란을 방지하기 위해, 서버 전용 axios 인스턴스를 따로 생성하여 withCredentials: false로 설정하거나, axiosConfig에서 withCredentials를 제거하고 클라이언트용 api 인스턴스 생성 시에만 명시적으로 withCredentials: true를 적용하는 것을 고려해볼 수 있습니다. 현재 구현 방식이 동작에는 문제가 없을 수 있으나, 명확성을 위해 제안합니다.
PR Type
Enhancement
Description
Axios 인스턴스 및 서버 API 클라이언트 구현
클라이언트/서버 환경 분리 요청 처리
React Query 및 개발자 도구 의존성 추가
자동 쿠키 관리 기능 포함
Diagram Walkthrough
File Walkthrough
axios.ts
Axios 클라이언트 인스턴스 설정lib/axios.ts
server-api.ts
서버 환경 API 클라이언트 구현lib/server-api.ts
package.json
React Query 및 Axios 의존성 추가package.json
pnpm-lock.yaml
패키지 잠금 파일 업데이트pnpm-lock.yaml
✨ 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.