251201_01_ENH : datatable, autocomplete, user관리 완성

This commit is contained in:
2025-12-02 13:45:35 +09:00
parent 74de3d58f7
commit 310506d9ef
45 changed files with 5313 additions and 368 deletions

View File

@@ -1,34 +1,32 @@
import { clientEnv } from "@/lib/env.client";
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
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<string, string>;
public readonly status: number;
public readonly data: unknown;
public readonly url: string;
private readonly headerMap: Record<string, string>;
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())
: {};
}
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<string, string> {
return this.headerMap;
}
get headers(): Record<string, string> {
return this.headerMap;
}
/** Convenience accessor for common trace headers */
get traceId(): string | undefined {
return this.headerMap["x-trace-id"] ?? this.headerMap["x-request-id"];
}
get traceId(): string | undefined {
return this.headerMap["x-trace-id"] ?? this.headerMap["x-request-id"];
}
}
export type QueryValue = string | string[] | undefined;
@@ -36,269 +34,263 @@ export type Query = Record<string, QueryValue>;
export type PathParams = Record<string, string | number | boolean>;
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<string, string>;
/** 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;
method?: HttpMethod;
pathParams?: PathParams;
query?: Query;
json?: unknown;
rawBody?: string;
form?: FormData;
headers?: Record<string, string>;
timeoutMs?: number;
suppressAlert?: boolean;
onAuthError?: () => void;
autoLogoutOnAuthError?: boolean;
expectText?: boolean;
expectBinary?: 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<string, string>;
/** Map server status/message to user-friendly text */
setErrorMessage?: (status: number, serverMsg?: string) => string;
getToken?: () => string | null;
defaultTimeoutMs?: number;
defaultHeaders?: Record<string, string>;
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;
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);
}
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<string, string>,
extra?: Record<string, string>
): Headers => {
const h = new Headers(base);
if (extra) for (const [k, v] of Object.entries(extra)) h.set(k, v);
return h;
const buildHeaders = (base: Record<string, string>, extra?: Record<string, string>): 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
*/
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 = 10_000,
defaultHeaders = { "content-type": "application/json" },
setErrorMessage,
} = opts;
const {
getToken,
defaultTimeoutMs = 60_000,
defaultHeaders = { "content-type": "application/json" },
setErrorMessage,
} = opts;
const request = async <T = unknown>(path: string, options: RequestOptions = {}): Promise<T> => {
// 1) URL
const replaced = replacePathParams(path, options.pathParams);
const request = async <T = unknown>(path: string, options: RequestOptions = {}): Promise<T> => {
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));
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<string, string> = { ...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);
try {
const res = await fetch(url.toString(), {
method: options.method ?? (body ? "POST" : "GET"),
headers,
body,
cache: "no-store",
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);
}
appendQuery(url, options.query);
const buffer = await res.arrayBuffer();
return buffer as T;
}
// 2) headers (defaults + token + per-call)
const base: Record<string, string> = { ...defaultHeaders };
const token = getToken?.();
if (token) base["authorization"] = `Bearer ${token}`;
const headers = buildHeaders(base, options.headers);
const ctype = res.headers.get("content-type") ?? "";
const isJson = isJsonContentType(ctype)
const rawText = await res.text().catch(() => "");
// 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);
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);
}
// 4) timeout
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs);
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;
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);
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
alert(`[${res.status}] ${msg}`);
}
};
// Convenience methods (all arrow functions)
const get = <T = unknown>(
path: string,
o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">
) => request<T>(path, { ...o, method: "GET" });
throw new HttpError(res.status, parsed, url.toString(), res.headers);
}
const post = <T = unknown>(
path: string,
json?: unknown,
o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">
) => request<T>(path, { ...o, method: "POST", json });
return parsed as T;
} catch (err: unknown) {
// ✅ 추가: 타임아웃/abort를 408로 매핑
if (isAbortError(err)) {
throw new HttpError(
408,
{ message: "요청 시간이 초과되었습니다.", timeoutMs: options.timeoutMs ?? defaultTimeoutMs },
url.toString()
);
}
const put = <T = unknown>(
path: string,
json?: unknown,
o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">
) => request<T>(path, { ...o, method: "PUT", json });
let code: string | undefined;
if (typeof err === "object" && err !== null) {
const anyErr = err as { cause?: unknown; code?: unknown };
const del = <T = unknown>(
path: string,
o?: Omit<RequestOptions, "method">
) => request<T>(path, { ...o, method: "DELETE" });
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;
}
const postForm = <T = unknown>(
path: string,
form: FormData,
o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">
) => request<T>(path, { ...o, method: "POST", form });
if (code === "ECONNREFUSED") {
throw new HttpError(404, { message: "백엔드 서버를 찾을 수 없습니다." }, url.toString());
}
const putForm = <T = unknown>(
path: string,
form: FormData,
o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">
) => request<T>(path, { ...o, method: "PUT", form });
throw err;
} finally {
clearTimeout(timer);
}
};
return { request, get, post, put, del, postForm, putForm };
const get = <T = unknown>(path: string, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "GET" });
const post = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "POST", json });
const put = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PUT", json });
const patch = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PATCH", json });
const del = <T = unknown>(path: string, o?: Omit<RequestOptions, "method">) =>
request<T>(path, { ...o, method: "DELETE" });
const postForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "POST", form });
const putForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PUT", form });
return { request, get, post, put, patch, del, postForm, putForm };
};
export const nextApi = createHttpClient(clientEnv.API_BASE);
export const nextApi = createHttpClient(clientEnv.API_BASE);