251113_01_ENH : 베이스 아키텍처 제작(향후 템플릿으로 사용)

This commit is contained in:
2025-11-13 14:59:10 +09:00
parent d107a9ce65
commit 1d713325ab
24 changed files with 1018 additions and 88 deletions

8
src/lib/env.client.ts Normal file
View File

@@ -0,0 +1,8 @@
export const clientEnv = {
API_BASE: process.env.NEXT_PUBLIC_API_BASE as string,
// 다른 클라이언트 전용 env들 추가 가능
};
if (!clientEnv.API_BASE) {
throw new Error("Missing env: NEXT_PUBLIC_API_BASE");
}

10
src/lib/env.server.ts Normal file
View File

@@ -0,0 +1,10 @@
const required = (name: string) => {
const v = process.env[name];
if (!v) throw new Error(`Missing env: ${name}`);
return v;
};
export const serverEnv = {
API_INTRANET: required("API_INTRANET"),
// 다른 서버 전용 env들 추가 가능
};

253
src/lib/http-client.ts Normal file
View File

@@ -0,0 +1,253 @@
// src/lib/http-client.ts
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<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())
: {};
}
/** Plain object headers (safe for logging/serialization) */
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"];
}
}
export type QueryValue = string | string[] | undefined;
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;
/** 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<string, string>;
/** 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<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
*/
export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => {
const {
getToken,
defaultTimeoutMs = 10_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 url = /^https?:\/\//i.test(replaced)
? new URL(replaced)
: new URL(replaced, baseURL);
appendQuery(url, options.query);
// 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);
// 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) {
if (res.status === 401) options.onAuthError?.();
if (!options.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: any) {
// 🔻 여기서 네트워크 레벨 에러 처리
const code = err?.cause?.code ?? err?.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 = <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 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, del, postForm, putForm };
};
export const nextApi = createHttpClient(clientEnv.API_BASE);

20
src/lib/utils.ts Normal file
View File

@@ -0,0 +1,20 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export function buildUrlWithParams(
targetPath: string,
from: Record<string, string | string[] | undefined>,
extra?: Record<string, string | undefined>,
) {
const qs = new URLSearchParams();
for (const [k, v] of Object.entries(from)) {
if (Array.isArray(v)) v.forEach((val) => qs.append(k, val));
else if (v !== undefined) qs.set(k, v);
}
if (extra) for (const [k, v] of Object.entries(extra)) if (v) qs.set(k, v);
return `${targetPath}${qs.toString() ? `?${qs}` : ""}`;
}