import { clientEnv } from "@/lib/env.client"; export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; 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()) : {}; } get headers(): Record { return this.headerMap; } 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 NextFetchOptions = { revalidate?: number; tags?: string[]; }; export type RequestOptions = { method?: HttpMethod; pathParams?: PathParams; query?: Query; json?: unknown; rawBody?: string; form?: FormData; headers?: Record; timeoutMs?: number; suppressAlert?: boolean; onAuthError?: () => void; autoLogoutOnAuthError?: boolean; expectText?: boolean; expectBinary?: boolean; cache?: RequestCache; // "force-cache" | "no-store" | ... next?: NextFetchOptions; // Next 서버 fetch 확장 옵션 }; export type HttpClientOptions = { getToken?: () => string | null; defaultTimeoutMs?: number; defaultHeaders?: Record; 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; }; const isAbortError = (err: unknown): boolean => { if (!err || typeof err !== "object") return false; const e = err as { name?: unknown; code?: unknown; message?: unknown }; return ( e.name === "AbortError" || // browser fetch abort e.code === "ABORT_ERR" || // some runtimes (typeof e.message === "string" && e.message.toLowerCase().includes("aborted")) ); }; const isJsonContentType = (ctype: string) => { const ct = (ctype ?? "").toLowerCase() return ct.includes("application/json") || ct.includes("+json") } export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => { const { getToken, defaultTimeoutMs = 60_000, defaultHeaders = { "content-type": "application/json" }, setErrorMessage, } = opts; const request = async (path: string, options: RequestOptions = {}): Promise => { const replaced = replacePathParams(path, options.pathParams); let url: URL; if (/^https?:\/\//i.test(replaced)) { url = new URL(replaced); } else if (replaced.startsWith("/")) { const base = new URL(baseURL); const joinedPath = `${base.pathname.replace(/\/+$/, "")}/${replaced.replace(/^\/+/, "")}`; url = new URL(base.toString()); url.pathname = joinedPath; } else { url = new URL(replaced, new URL(baseURL)); } appendQuery(url, options.query); const base: Record = { ...defaultHeaders }; const token = getToken?.(); if (token) base["authorization"] = `Bearer ${token}`; const headers = buildHeaders(base, options.headers); let body: BodyInit | undefined; if (options.form) { headers.delete("content-type"); 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); } const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs); const isServer = typeof window === "undefined"; const cacheMode: RequestCache = options.cache ?? (isServer && options.next ? "force-cache" : "no-store"); const nextOpt = isServer ? options.next : undefined; try { const res = await fetch(url.toString(), { method: options.method ?? (body ? "POST" : "GET"), headers, body, cache: cacheMode, ...(nextOpt ? ({ next: nextOpt } as any) : {}), signal: controller.signal, }); if (options.expectBinary) { if (!res.ok) { const rawText = await res.text().catch(() => ""); const ctype = res.headers.get("content-type") ?? "" const isJson = isJsonContentType(ctype) let parsedError: unknown; if (isJson && rawText) { try { parsedError = JSON.parse(rawText); } catch { parsedError = rawText; } } else { parsedError = rawText || null; } const autoLogout = options.autoLogoutOnAuthError ?? true; const suppressAlert = options.suppressAlert ?? true; if (res.status === 401) options.onAuthError?.(); if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") { try { window.location.replace("/logout"); } catch {} throw new HttpError(res.status, parsedError, url.toString(), res.headers); } if (!suppressAlert && typeof window !== "undefined") { const serverMsg = typeof parsedError === "object" && parsedError !== null && "message" in parsedError ? String((parsedError as { message?: unknown }).message ?? "") : typeof parsedError === "string" ? parsedError : undefined; const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`); alert(`[${res.status}] ${msg}`); } throw new HttpError(res.status, parsedError, url.toString(), res.headers); } const buffer = await res.arrayBuffer(); return buffer as T; } const ctype = res.headers.get("content-type") ?? ""; const isJson = isJsonContentType(ctype) const rawText = await res.text().catch(() => ""); const parsed: unknown = options.expectText ? rawText : isJson ? rawText ? JSON.parse(rawText) : null : rawText; if (!res.ok) { const autoLogout = options.autoLogoutOnAuthError ?? true; const suppressAlert = options.suppressAlert ?? true; if (res.status === 401) options.onAuthError?.(); if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") { try { window.location.replace("/logout"); } catch {} 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}`); alert(`[${res.status}] ${msg}`); } throw new HttpError(res.status, parsed, url.toString(), res.headers); } return parsed as T; } catch (err: unknown) { if (isAbortError(err)) { throw new HttpError( 408, { message: "요청 시간이 초과되었습니다.", timeoutMs: options.timeoutMs ?? defaultTimeoutMs }, url.toString() ); } 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") { throw new HttpError(404, { message: "백엔드 서버를 찾을 수 없습니다." }, url.toString()); } throw err; } finally { clearTimeout(timer); } }; 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 patch = (path: string, json?: unknown, o?: Omit) => request(path, { ...o, method: "PATCH", 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, patch, del, postForm, putForm }; }; export const nextApi = createHttpClient(clientEnv.API_BASE);