[FEAT] Vite 프록시 도입을 통한 개발 환경 개선 및 API 호출 리팩터링 (#154)#155
Conversation
aaaaaattt
left a comment
There was a problem hiding this comment.
merge 이후 우선 바로 dev 브랜치 기준으로 수동으로 배포해보겠습니다
| body: JSON.stringify({ content, rating }), | ||
| const url = `/api/applications/${applicationId}/comments/${commentId}`; | ||
| const response = await fetch(url, { | ||
| method: 'PUT', |
There was a problem hiding this comment.
스웨거/명세 기준으로 지원서 댓글 수정은 PUT이 아니라 PATCH 인 것 같습니다
WalkthroughRefactors API calls to use relative paths and Vite dev-server proxying; adds explicit response.ok checks and throws on errors across endpoints; changes comment update from PUT to PATCH; removes status parameter from applicants fetch while leaving it in one hook's queryKey; converts vite.config.ts to an env-aware function that sets server.proxy. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Dev as Browser (Dev)
participant Vite as Vite Dev Server (Proxy)
participant API as Backend
Dev->>Vite: Request /api/...
Note over Vite: Proxy rule matches /api → forward to env.VITE_API_BASE_URL
Vite->>API: Forward /api/...
API-->>Vite: Response
Vite-->>Dev: Proxied response (CORS-free)
sequenceDiagram
autonumber
participant UI as Client UI
participant ClientAPI as client API module
participant Server as Backend
UI->>ClientAPI: updateComment(id, payload)
ClientAPI->>Server: PATCH /api/.../comments/{id} (JSON)
alt response.ok
Server-->>ClientAPI: 2xx + body
ClientAPI-->>UI: parsed JSON
else not ok
Server-->>ClientAPI: Error status + body
ClientAPI-->>UI: throw Error(status, message)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~30 minutes Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
src/pages/admin/ApplicationDetail/api/comments.ts(3 hunks)src/pages/admin/ApplicationDetail/api/detailApplication.ts(1 hunks)src/pages/admin/ClubDetailEdit/api/clubDetailEdit.ts(1 hunks)src/pages/admin/Dashboard/api/applicant.ts(1 hunks)src/pages/admin/Dashboard/hooks/useApplicants.ts(1 hunks)src/pages/user/Apply/api/apply.ts(2 hunks)src/pages/user/ClubDetail/api/clubDetail.ts(1 hunks)src/pages/user/Main/api/club.ts(1 hunks)vite.config.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
src/pages/admin/ApplicationDetail/api/detailApplication.ts (1)
src/pages/admin/ApplicationDetail/types/detailApplication.ts (1)
DetailApplication(3-19)
src/pages/user/ClubDetail/api/clubDetail.ts (1)
src/pages/user/ClubDetail/types/clubDetail.ts (1)
ClubDetail(3-20)
src/pages/admin/Dashboard/api/applicant.ts (1)
src/pages/admin/Dashboard/types/dashboard.ts (1)
ApplicantData(14-22)
src/pages/admin/Dashboard/hooks/useApplicants.ts (1)
src/pages/admin/Dashboard/api/applicant.ts (1)
fetchApplicants(3-13)
src/pages/admin/ClubDetailEdit/api/clubDetailEdit.ts (1)
src/pages/admin/ClubDetailEdit/types/clubDetailEdit.ts (1)
ClubDetailEdit(3-3)
src/pages/admin/ApplicationDetail/api/comments.ts (1)
src/mocks/repositories/applicant.ts (1)
deleteComment(131-138)
🔇 Additional comments (4)
src/pages/user/Apply/api/apply.ts (2)
8-14: LGTM! Clean refactor to relative endpoint with proper error handling.The fetch call now uses the proxy-relative path and includes appropriate response validation. The error message is clear and user-facing.
16-34: LGTM! Consistent pattern applied to POST request.The changes follow the same pattern as
fetchApplicationForm, using relative paths and proper error handling.src/pages/admin/ApplicationDetail/api/detailApplication.ts (1)
3-12: LGTM! Proper refactor with error handling.The relative endpoint and response validation are correctly implemented.
src/pages/admin/Dashboard/api/applicant.ts (1)
3-13: LGTM! Simplified API with enhanced error handling.The removal of the
statusparameter and the shift to a relative endpoint are correct. The enhanced error handling that includes both HTTP status and response text is an improvement.
| const { data, isLoading, error } = useQuery({ | ||
| queryKey: ['applicants', clubId, status], | ||
| queryFn: () => fetchApplicants(clubId, status), | ||
| queryFn: () => fetchApplicants(clubId), | ||
| staleTime: 1000 * 60 * 2, | ||
| }); |
There was a problem hiding this comment.
Fix cache key to match API call signature.
The queryKey at Line 14 includes status, but the API call at Line 15 no longer passes status to fetchApplicants. This creates a cache key mismatch:
- Different
statusvalues create separate cache entries - But all entries fetch the same unfiltered data
- This wastes memory and creates confusing cache behavior
Apply this diff to align the cache key with the API call:
const { data, isLoading, error } = useQuery({
- queryKey: ['applicants', clubId, status],
+ queryKey: ['applicants', clubId],
queryFn: () => fetchApplicants(clubId),
staleTime: 1000 * 60 * 2,
});If client-side filtering by status is still needed, implement it in the hook's return value instead:
return {
data: status && status !== '전체'
? (data || []).filter(applicant => applicant.status === status)
: (data || []),
isLoading,
error,
};🤖 Prompt for AI Agents
In src/pages/admin/Dashboard/hooks/useApplicants.ts around lines 13 to 17, the
queryKey currently includes `status` while the queryFn calls
`fetchApplicants(clubId)` without `status`, causing cache key mismatch; remove
`status` from the `queryKey` so it matches the actual API call, and if you still
need client-side filtering, apply the provided filtering logic in the hook's
return value to filter `data` by `status` (treating '전체' as no filter) while
returning `isLoading` and `error` unchanged.
| const url = `/api/clubs?category=${filter}`; | ||
| const response = await fetch(url); |
There was a problem hiding this comment.
Critical: Relative /api requests will 404 in production
By dropping import.meta.env.VITE_API_BASE_URL and hardcoding /api, every fetch now assumes a same-origin reverse proxy. In production builds there is no Vite dev proxy, so deployments that serve the SPA from S3/CloudFront (or any origin different from the backend) will start issuing /api/... requests to the static host and immediately fail with 404/CORS. We just lost the ability to point the frontend at the real backend domain.
Please keep using the environment-provided base URL (and only fall back to /api when it is intentionally empty) and apply the same fix to every API module touched in this PR. Example patch:
- const url = `/api/clubs?category=${filter}`;
- const response = await fetch(url);
+ const endpoint = `/clubs?category=${filter}`;
+ const baseUrl = import.meta.env.VITE_API_BASE_URL ?? '';
+ const response = await fetch(`${baseUrl}${endpoint}`);This preserves production correctness while still letting you set VITE_API_BASE_URL="" for dev to leverage the proxy. Please reflect the same pattern across the other updated API files.
📝 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.
| const url = `/api/clubs?category=${filter}`; | |
| const response = await fetch(url); | |
| const endpoint = `/clubs?category=${filter}`; | |
| const baseUrl = import.meta.env.VITE_API_BASE_URL ?? ''; | |
| const response = await fetch(`${baseUrl}${endpoint}`); |
🤖 Prompt for AI Agents
In src/pages/user/Main/api/club.ts around lines 9-10, the code hardcodes a
relative "/api" base which will 404 in production when the frontend is served
from a different origin; restore use of import.meta.env.VITE_API_BASE_URL with a
fallback to "/api" (e.g. const base = import.meta.env.VITE_API_BASE_URL ||
'/api') and build the fetch URL by joining base and the path safely (avoid
duplicate slashes), then replace the hardcoded const url assignment with this
composed URL; apply the same pattern to every other API module changed in this
PR.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/pages/admin/ApplicationDetail/api/detailApplication.ts (1)
17-28: Past review addressed; consider more specific return typing.Good work addressing the previous review comment—the return type is now
Promise<unknown>and matches the returnedresponse.json(). The authentication concern from the previous comment applies here as well.As a minor refinement, consider typing the return value more specifically if the response shape is known. For example:
+type UpdateStatusResponse = { message: string; updatedAt: string }; + export const updateApplicationStatus = async ( applicationId: number, status: DetailApplication['status'], -): Promise<unknown> => { +): Promise<UpdateStatusResponse> => {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/pages/admin/ApplicationDetail/api/detailApplication.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/pages/admin/ApplicationDetail/api/detailApplication.ts (1)
src/pages/admin/ApplicationDetail/types/detailApplication.ts (1)
DetailApplication(3-19)
🔇 Additional comments (1)
src/pages/admin/ApplicationDetail/api/detailApplication.ts (1)
7-11: Confirm authentication for this fetch call
No existing fetch invocations includecredentialsor anAuthorizationheader. Verify whether this endpoint requires auth; if so, update the request to includecredentials: 'include'or the appropriateAuthorizationheader.
…s-proxy#154 [FEAT] Vite 프록시 도입을 통한 개발 환경 개선 및 API 호출 리팩터링 (#154)
…s-proxy#154 [FEAT] Vite 프록시 도입을 통한 개발 환경 개선 및 API 호출 리팩터링 (#154)
#️⃣연관된 이슈
📝작업 내용
로컬 개발 환경에서 백엔드 API 호출 시 발생하는 CORS 오류 해결
1. Vite 프록시 설정 추가 (vite.config.ts)
server.proxy 옵션을 사용하여 /api 경로로 들어오는 모든 요청을 백엔드 서버로 전달
2. API 호출 방식 전체 리팩터링
기존에 import.meta.env.VITE_API_BASE_URL을 직접 사용하던 모든 fetch 함수를 프록시를 통하는 상대 경로(/api/...)를 사용하도록 수정
변경 전
변경 후
💬리뷰 요구사항(선택)
Summary by CodeRabbit
Bug Fixes
Refactor
Chores