[feat] negodata/front: 상품·협력사 목록 서버 페이지네이션·검색 연동(재사용 useServerList) + 카드·견적 UI
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
7c244bca27
commit
dd03c2aecd
28 files changed
+1104
-554
No files matched your search
@@ -9,12 +9,52 @@
|
||||
// baseURL — compose 의 VITE_API_BASE_URL 로 주입, 없으면 9400 폴백.
|
||||
const BASE_URL = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9400';
|
||||
|
||||
// 토큰 보관소 — 인증 연동 시 로그인 후 setAccessToken()으로 주입한다(현재 목업 단계에선 미사용).
|
||||
// 토큰 보관소 — 로그인 후 setAccessToken()으로 주입. localStorage(auth/service 와 동일 키)와 동기화.
|
||||
const ACCESS_KEY = 'negodata.accessToken';
|
||||
const REFRESH_KEY = 'negodata.refreshToken';
|
||||
|
||||
let accessToken: string | null = null;
|
||||
export const setAccessToken = (token: string | null) => {
|
||||
accessToken = token;
|
||||
};
|
||||
|
||||
// 동시 다발 434(액세스 토큰 만료)를 단 한 번의 refresh 로 합치기 위한 in-flight 프라미스.
|
||||
let refreshInFlight: Promise<string | null> | null = null;
|
||||
|
||||
// refresh 토큰으로 access 재발급. 성공 시 새 access 토큰, 실패 시 null.
|
||||
async function refreshAccessToken(): Promise<string | null> {
|
||||
if (refreshInFlight) return refreshInFlight;
|
||||
refreshInFlight = (async () => {
|
||||
try {
|
||||
const refresh = localStorage.getItem(REFRESH_KEY);
|
||||
if (!refresh) return null;
|
||||
// refresh 토큰은 Authorization 헤더(Bearer)로 보낸다(auth/service restore() 와 동일 규약).
|
||||
const res = await fetch(`${BASE_URL}/v1/auth/refresh_token`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${refresh}` },
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const refreshed = await res.json().catch(() => null);
|
||||
const newToken: string | undefined = refreshed?.access_token;
|
||||
if (!newToken || refreshed?.result?.success === false) return null;
|
||||
localStorage.setItem(ACCESS_KEY, newToken);
|
||||
accessToken = newToken;
|
||||
return newToken;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
refreshInFlight = null;
|
||||
}
|
||||
})();
|
||||
return refreshInFlight;
|
||||
}
|
||||
|
||||
function clearTokens() {
|
||||
localStorage.removeItem(ACCESS_KEY);
|
||||
localStorage.removeItem(REFRESH_KEY);
|
||||
accessToken = null;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
@@ -42,19 +82,6 @@ export const customFetch = async <T>(
|
||||
): Promise<T> => {
|
||||
const { url, method, params, data, signal } = config;
|
||||
|
||||
// [요청 인터셉터] 헤더 병합: config → options 순으로 덮어쓴다.
|
||||
const headers = new Headers(config.headers);
|
||||
if (options?.headers) {
|
||||
new Headers(options.headers).forEach((v, k) => headers.set(k, v));
|
||||
}
|
||||
if (data != null && !headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
// 토큰이 있으면 Authorization 자동 주입
|
||||
if (accessToken) {
|
||||
headers.set('Authorization', `Bearer ${accessToken}`);
|
||||
}
|
||||
|
||||
// 쿼리스트링 직렬화 (null/undefined 값은 제외)
|
||||
const queryString = params
|
||||
? new URLSearchParams(
|
||||
@@ -67,13 +94,37 @@ export const customFetch = async <T>(
|
||||
(url.startsWith('http') ? url : `${BASE_URL}${url}`) +
|
||||
(queryString ? `?${queryString}` : '');
|
||||
|
||||
const response = await fetch(requestUrl, {
|
||||
...options,
|
||||
method,
|
||||
headers,
|
||||
body: data != null ? JSON.stringify(data) : options?.body,
|
||||
signal,
|
||||
});
|
||||
// [요청 인터셉터] 토큰을 받아 헤더를 구성하고 한 번 호출(만료 재시도 시 새 토큰으로 재구성).
|
||||
const doFetch = (token: string | null) => {
|
||||
const headers = new Headers(config.headers);
|
||||
if (options?.headers) {
|
||||
new Headers(options.headers).forEach((v, k) => headers.set(k, v));
|
||||
}
|
||||
if (data != null && !headers.has('Content-Type')) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
if (token) headers.set('Authorization', `Bearer ${token}`);
|
||||
return fetch(requestUrl, {
|
||||
...options,
|
||||
method,
|
||||
headers,
|
||||
body: data != null ? JSON.stringify(data) : options?.body,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
let response = await doFetch(accessToken);
|
||||
|
||||
// 434(액세스 토큰 만료) → refresh 로 재발급 후 1회 재시도. auth 엔드포인트 자신은 제외(무한루프 방지).
|
||||
const isAuthEndpoint = url.includes('/v1/auth/refresh_token') || url.includes('/v1/auth/login');
|
||||
if ((response.status === 434 || response.status === 401) && !isAuthEndpoint) {
|
||||
const newToken = await refreshAccessToken();
|
||||
if (newToken) {
|
||||
response = await doFetch(newToken);
|
||||
} else {
|
||||
clearTokens(); // refresh 실패 → 토큰 폐기(다음 로드/가드에서 로그인으로 유도)
|
||||
}
|
||||
}
|
||||
|
||||
// [응답 인터셉터] 본문 파싱 (204/빈 응답 대응)
|
||||
const isJson = response.headers.get('content-type')?.includes('application/json');
|
||||
@@ -82,7 +133,6 @@ export const customFetch = async <T>(
|
||||
|
||||
// fetch는 4xx/5xx도 resolve하므로 직접 throw → React Query가 error로 처리
|
||||
if (!response.ok) {
|
||||
// TODO: 401이면 refresh 토큰으로 재발급 후 재시도 로직 추가 위치
|
||||
throw new ApiError(response.status, response.statusText, body);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user