Files
2026-09-15 10:00:42 +09:00

255 lines
7.3 KiB
TypeScript

/**
* 📄 API Utility
* API 호출 유틸리티 파일
*
* - 다양한 HTTP 메소드의 API 호출 함수 (GET, POST, PUT, DELETE)
* - 쿠키 기반 인증 토큰 관리 및 사용자 조회
* - 특정 서비스 (DC, CMS, GeoServer) 호출 지원
* - Axios 및 Fetch 기반 HTTP 요청 처리
* - 타입 안전성 보장을 위한 인터페이스 활용
* - 에러 핸들링 및 응답 처리 표준화
*/
import { useEffect, useState } from "react";
import axios from 'axios';
import { AxiosError } from 'axios';
import { CLAIM_NAME, SITE_ID } from "@/shared/config";
import { tokenManager } from "@/entities/auth/lib/token-manager";
import { getRemainingMs } from "@common/auth";
// 기존 shared/api barrel의 인증 client 초기화 부수효과를 불러오지 않는 순수 transport다.
import { createHttpTransport } from "@/shared/api/http-transport";
const BASE_URL = '/sewerage-service/api';
const DEFAULT_HEADERS = {
"X-Site-Id": SITE_ID,
};
const LOGIN_PAGE_URL =
process.env.NEXT_PUBLIC_CM_LOGIN_PAGE_URL || "/auth/login";
const withSiteIdHeaders = (headers: HeadersInit = {}) => ({
...headers,
...DEFAULT_HEADERS,
});
const resolveApiUrl = (url: string) =>
url.startsWith('/') ? `${url}` : `${BASE_URL}/${url}`;
const handleUnauthorizedResponse = () => {
if (typeof window === "undefined") return;
const accessToken = tokenManager.getToken(CLAIM_NAME);
const remainingMs = accessToken ? getRemainingMs(accessToken) : null;
const isExpired = remainingMs === null || remainingMs <= 0;
if (!isExpired) return;
tokenManager.clearAuthToken();
const isLoginPage =
window.location.pathname === "/auth/login" ||
window.location.pathname.startsWith("/auth/login/");
if (!isLoginPage) {
window.location.assign(LOGIN_PAGE_URL);
}
};
// 기존 import 경로를 유지하는 호환 진입점이다. HTTP 처리는 shared/api가 소유한다.
const httpTransport = createHttpTransport({
baseUrl: BASE_URL,
headers: DEFAULT_HEADERS,
onUnauthorized: handleUnauthorizedResponse,
});
export const { getData, postData, putData, getRawJson, postRawJson, deleteData } =
httpTransport;
const parseDownloadFileName = (contentDisposition: string | null) => {
if (!contentDisposition) return undefined;
const utf8Match = contentDisposition.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);
if (utf8Match?.[1]) {
return decodeURIComponent(utf8Match[1].trim());
}
const plainMatch = contentDisposition.match(/filename\s*=\s*"?([^\";]+)"?/i);
return plainMatch?.[1]?.trim();
};
export const postBlobData = async (
url: string,
data: object,
): Promise<{ blob: Blob; fileName?: string }> => {
const res = await fetch(resolveApiUrl(url), {
method: "POST",
headers: withSiteIdHeaders({
"Content-Type": "application/json",
}),
body: JSON.stringify(data),
});
if (res.status === 401) {
handleUnauthorizedResponse();
}
if (!res.ok) {
const errorText = await res.text().catch(() => "");
throw new Error(
`Failed to fetch blob: ${res.status} ${res.statusText}${errorText ? ` - ${errorText.slice(0, 200)}` : ""} (${url})`,
);
}
return {
blob: await res.blob(),
fileName: parseDownloadFileName(res.headers.get("content-disposition")),
};
};
export const postMutiPart = async (url: string, data: FormData): Promise<any> => {
try {
const res = await axios.post(resolveApiUrl(url), data, {
headers: DEFAULT_HEADERS,
timeout: 600000, // 10분
});
console.log('postMultiPart response:', res);
return res.data.data;
} catch (error) {
if (error instanceof AxiosError) {
const responseBody = error.response?.data;
const serverMessage =
typeof responseBody?.message === 'string' && responseBody.message.trim()
? responseBody.message.trim()
: typeof responseBody?.error?.message === 'string' && responseBody.error.message.trim()
? responseBody.error.message.trim()
: typeof responseBody === 'string' && responseBody.trim()
? responseBody.trim()
: null;
const nextError = new Error(
serverMessage ?? `Multipart request failed: ${error.response?.status ?? 'UNKNOWN'} ${error.response?.statusText ?? ''}`.trim(),
) as Error & { status?: number; body?: unknown };
nextError.status = error.response?.status;
nextError.body = responseBody;
throw nextError;
}
throw error;
}
};
export const getBlobData = async (url: string): Promise<Blob> => {
const res = await fetch(resolveApiUrl(url), {
method: "GET",
headers: withSiteIdHeaders(),
});
if (res.status === 401) {
handleUnauthorizedResponse();
}
if (!res.ok) {
const errorText = await res.text().catch(() => "");
throw new Error(
`Failed to fetch blob: ${res.status} ${res.statusText}${errorText ? ` - ${errorText.slice(0, 200)}` : ""} (${url})`,
);
}
return res.blob();
};
export const getBlobDataWithHeaders = async (
url: string,
): Promise<{ blob: Blob; fileName?: string; headers: Headers }> => {
const res = await fetch(resolveApiUrl(url), {
method: "GET",
headers: withSiteIdHeaders(),
});
if (res.status === 401) {
handleUnauthorizedResponse();
}
if (!res.ok) {
const errorText = await res.text().catch(() => "");
throw new Error(
`Failed to fetch blob: ${res.status} ${res.statusText}${errorText ? ` - ${errorText.slice(0, 200)}` : ""} (${url})`,
);
}
return {
blob: await res.blob(),
fileName: parseDownloadFileName(res.headers.get("content-disposition")),
headers: res.headers,
};
};
// DC API 호출
export const getDcData = async (url: string, resType: string = "json"): Promise<any> => {
const res = await fetch('/dc-service' + url, {
method: "GET",
headers: withSiteIdHeaders(),
});
if (res.status === 401) {
handleUnauthorizedResponse();
}
if (res.ok) {
let data;
if (resType === "json") data = await res.json();
else if (resType === "blob") data = await res.blob();
return data;
}
throw new Error('Failed to fetch data');
};
// CMS API 호출
export const getCmsData = async (url: string, data?: object): Promise<any> => {
const res = await fetch('/cms-service' + url, {
method: "GET",
headers: withSiteIdHeaders(),
});
if (res.status === 401) {
handleUnauthorizedResponse();
}
if (res.ok) {
const data = await res.json();
return data;
}
throw new Error('Failed to fetch data');
};
// GeoServer API 호출
export const getGeoData = async (url: string, data?: object): Promise<any> => {
const res = await fetch('/geoserver' + url, {
method: "GET",
headers: withSiteIdHeaders(),
});
if (res.status === 401) {
handleUnauthorizedResponse();
}
if (res.ok) {
const data = await res.json();
return data;
}
throw new Error('Failed to fetch data');
};
export function getCookie(name: string) {
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match && match[2]) {
return decodeURIComponent(match[2]);
}
return null;
}
export const useCookieAuth = () => {
const [data, setData] = useState("");
useEffect(() => {
const fetch = async () => {
const result = getCookie("Authorization");
if (result) {
setData(result);
}
};
fetch();
console.log("useCookieAuth 호출");
}, []);
return data;
};