import { clientEnv } from "@/lib/env.client"; export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE"; export class HttpError extends Error { public readonly status: number; public readonly data: unknown; public readonly url: string; private readonly headerMap: Record; constructor(status: number, data: unknown, url: string, headers?: Headers) { super(`HTTP ${status}`); this.name = "HttpError"; this.status = status; this.data = data; this.url = url; this.headerMap = headers && typeof headers.entries === "function" ? Object.fromEntries(headers.entries()) : {}; } /** Plain object headers (safe for logging/serialization) */ get headers(): Record { return this.headerMap; } /** Convenience accessor for common trace headers */ get traceId(): string | undefined { return this.headerMap["x-trace-id"] ?? this.headerMap["x-request-id"]; } } export type QueryValue = string | string[] | undefined; export type Query = Record; export type PathParams = Record; export type RequestOptions = { /** HTTP method (default: GET or POST when body exists) */ method?: HttpMethod; /** Replace placeholders in path, e.g., /users/:id */ pathParams?: PathParams; /** Query string key-values (arrays supported) */ query?: Query; /** JSON body (auto-serialized) */ json?: unknown; /** Send raw text body */ rawBody?: string; /** Send multipart/form-data */ form?: FormData; /** Extra headers (merged over defaults) */ headers?: Record; /** Per-request timeout (ms), default from client */ timeoutMs?: number; /** Suppress user alert on error */ suppressAlert?: boolean; /** Hook for 401 responses */ onAuthError?: () => void; /** * 401/403(토큰 만료 포함) 수신 시 자동으로 /logout 으로 이동할지 여부 * - 기본값: true * - 요청 단위로 false 설정하면 자동 로그아웃을 건너뜁니다. */ autoLogoutOnAuthError?: boolean; /** Force treat response as text (skip JSON parse) */ expectText?: boolean; }; export type HttpClientOptions = { /** Provide latest token per request (e.g., from storage) */ getToken?: () => string | null; /** Default timeout (ms) */ defaultTimeoutMs?: number; /** Default headers (e.g., content-type) */ defaultHeaders?: Record; /** Map server status/message to user-friendly text */ setErrorMessage?: (status: number, serverMsg?: string) => string; }; const replacePathParams = (path: string, params?: PathParams): string => { if (!params) return path; let out = path; for (const [k, v] of Object.entries(params)) { const ph = `:${k}`; if (out.includes(ph)) out = out.replace(ph, encodeURIComponent(String(v))); } return out; }; const appendQuery = (u: URL, query?: Query): void => { if (!query) return; for (const [k, v] of Object.entries(query)) { if (Array.isArray(v)) v.forEach((it) => u.searchParams.append(k, it)); else if (v !== undefined) u.searchParams.set(k, v); } }; const buildHeaders = ( base: Record, extra?: Record ): Headers => { const h = new Headers(base); if (extra) for (const [k, v] of Object.entries(extra)) h.set(k, v); return h; }; /** * Create a minimal, fetch-based HTTP client with: * - path params (:id), query, JSON/FormData/raw body * - default/extra headers + token injection * - timeout, 401 hook, optional alert suppression */ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => { const { getToken, defaultTimeoutMs = 10_000, defaultHeaders = { "content-type": "application/json" }, setErrorMessage, } = opts; const request = async (path: string, options: RequestOptions = {}): Promise => { // 1) URL const replaced = replacePathParams(path, options.pathParams); // NOTE: // new URL('/x', 'http://host/base') => 'http://host/x' (pathname from base is dropped) // We want to preserve base pathname (e.g., '/api/v1') when caller passes an absolute path like '/auth/login'. let url: URL; if (/^https?:\/\//i.test(replaced)) { // Fully-qualified URL: use as-is url = new URL(replaced); } else if (replaced.startsWith('/')) { // Absolute-like path: merge with base's pathname const base = new URL(baseURL); const joinedPath = `${base.pathname.replace(/\/+$/, '')}/${replaced.replace(/^\/+/, '')}`; url = new URL(base.toString()); url.pathname = joinedPath; } else { // Relative path: URL API will correctly join with base pathname url = new URL(replaced, new URL(baseURL)); } appendQuery(url, options.query); // 2) headers (defaults + token + per-call) const base: Record = { ...defaultHeaders }; const token = getToken?.(); if (token) base["authorization"] = `Bearer ${token}`; const headers = buildHeaders(base, options.headers); // 3) body let body: BodyInit | undefined; if (options.form) { headers.delete("content-type"); // let browser set multipart boundary body = options.form; } else if (options.rawBody !== undefined) { if (!headers.has("content-type")) headers.set("content-type", "text/plain;charset=utf-8"); body = options.rawBody; } else if (options.json !== undefined) { if (!headers.has("content-type")) headers.set("content-type", "application/json"); body = typeof options.json === "string" ? options.json : JSON.stringify(options.json); } // 4) timeout const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs); try { // 5) fetch const res = await fetch(url.toString(), { method: options.method ?? (body ? "POST" : "GET"), headers, body, cache: "no-store", signal: controller.signal, }); // 6) parse const ctype = res.headers.get("content-type") ?? ""; const isJson = ctype.includes("application/json"); const rawText = await res.text().catch(() => ""); const parsed: unknown = options.expectText ? rawText : isJson ? rawText ? JSON.parse(rawText) : null : rawText; // 7) error (HTTP status 에러) if (!res.ok) { const autoLogout = options.autoLogoutOnAuthError ?? true; const suppressAlert = options.suppressAlert ?? true; // 401 훅 호출 (기존 동작 유지) if (res.status === 401) options.onAuthError?.(); // 401 또는 403 (토큰 만료 포함) 시 자동 로그아웃 처리 if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") { // 사용자 알림은 띄우지 않고 바로 로그아웃 라우팅으로 이동 try { window.location.replace("/logout"); } catch { // noop } // 이후 로직 진행을 막기 위해 에러를 던지기 throw new HttpError(res.status, parsed, url.toString(), res.headers); } if (!suppressAlert && typeof window !== "undefined") { const serverMsg = typeof parsed === "object" && parsed !== null && "message" in parsed ? String((parsed as { message?: unknown }).message ?? "") : typeof parsed === "string" ? parsed : undefined; const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`); // eslint-disable-next-line no-alert alert(`[${res.status}] ${msg}`); } throw new HttpError(res.status, parsed, url.toString(), res.headers); } return parsed as T; } catch (err: unknown) { let code: string | undefined; if (typeof err === "object" && err !== null) { const anyErr = err as { cause?: unknown; code?: unknown }; if (anyErr.cause && typeof anyErr.cause === "object") { const cause = anyErr.cause as { code?: unknown }; if (typeof cause.code === "string") { code = cause.code; } } if (!code && typeof anyErr.code === "string") { code = anyErr.code; } } // 🔻 여기서 네트워크 레벨 에러 처리 if (code === "ECONNREFUSED") { // 네트워크 연결 실패 → HttpError(404)로 변환 throw new HttpError( 404, { message: "백엔드 서버를 찾을 수 없습니다." }, url.toString(), ); } // 그 외 에러는 그대로 던지기 throw err; } finally { // timeout 정리 clearTimeout(timer); } }; // Convenience methods (all arrow functions) const get = ( path: string, o?: Omit ) => request(path, { ...o, method: "GET" }); const post = ( path: string, json?: unknown, o?: Omit ) => request(path, { ...o, method: "POST", json }); const put = ( path: string, json?: unknown, o?: Omit ) => request(path, { ...o, method: "PUT", json }); const del = ( path: string, o?: Omit ) => request(path, { ...o, method: "DELETE" }); const postForm = ( path: string, form: FormData, o?: Omit ) => request(path, { ...o, method: "POST", form }); const putForm = ( path: string, form: FormData, o?: Omit ) => request(path, { ...o, method: "PUT", form }); return { request, get, post, put, del, postForm, putForm }; }; export const nextApi = createHttpClient(clientEnv.API_BASE);