260702_01_ENH: 1차 중간 정리

This commit is contained in:
2026-07-02 08:21:22 +09:00
parent 510b4a9e68
commit d628da3192
36 changed files with 2443 additions and 68 deletions

100
src/http/error-policy.ts Normal file
View File

@@ -0,0 +1,100 @@
import type {
ErrorMessageResolver,
ErrorNotifier,
HttpError,
} from "./http-client.js";
let logoutRedirectStarted = false;
export type LogoutRedirectOptions = {
logoutPath?: string;
excludedPaths?: string[];
};
export const getServerMessage = (payload: unknown): string | undefined => {
if (typeof payload === "string") {
return payload;
}
if (typeof payload === "object" && payload !== null && "message" in payload) {
const message = (payload as { message?: unknown }).message;
return typeof message === "string" ? message : undefined;
}
return undefined;
};
export const redirectToLogout = (options: LogoutRedirectOptions = {}): void => {
if (typeof window === "undefined") {
return;
}
if (logoutRedirectStarted) {
return;
}
const logoutPath = options.logoutPath ?? "/logout";
const excludedPaths = options.excludedPaths ?? ["/login", logoutPath];
if (excludedPaths.includes(window.location.pathname)) {
return;
}
logoutRedirectStarted = true;
window.location.replace(logoutPath);
};
export const defaultResolveErrorMessage: ErrorMessageResolver = (
status,
serverMessage,
) => {
if (serverMessage) {
return serverMessage;
}
switch (status) {
case 400:
return "잘못된 요청입니다.";
case 404:
return "요청한 대상을 찾을 수 없습니다.";
case 408:
return "요청 시간이 초과되었습니다.";
case 500:
return "서버 오류가 발생했습니다.";
default:
return "요청 처리 중 오류가 발생했습니다.";
}
};
export const defaultNotifyError: ErrorNotifier = (message, error) => {
if (typeof window === "undefined") {
return;
}
window.alert(`[${error.status}] ${message}`);
};
export const showErrorMessage = (
error: HttpError,
options?: {
resolveErrorMessage?: ErrorMessageResolver;
notifyError?: ErrorNotifier;
},
): void => {
const serverMessage = getServerMessage(error.data);
const resolveErrorMessage =
options?.resolveErrorMessage ?? defaultResolveErrorMessage;
const notifyError = options?.notifyError ?? defaultNotifyError;
const message = resolveErrorMessage(error.status, serverMessage);
notifyError(message, error);
};

766
src/http/http-client.ts Normal file
View File

@@ -0,0 +1,766 @@
import { redirectToLogout, showErrorMessage } from "./error-policy.js";
export const DEFAULT_HTTP_TIMEOUT_MS = 60_000;
export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
export type HttpErrorHandler = (error: HttpError) => void;
export type ErrorMessageResolver = (
status: number,
serverMessage?: string,
) => string;
export type ErrorNotifier = (message: string, error: HttpError) => void;
export class HttpError extends Error {
public readonly status: number;
public readonly data: unknown;
public readonly url: string;
private readonly headerMap: Record<string, string>;
public constructor(
status: number,
data: unknown,
url: string,
headers?: Headers,
) {
super(`HTTP ${status}`);
this.name = "HttpError";
this.status = status;
this.data = data;
this.url = url;
const headerMap: Record<string, string> = {};
headers?.forEach((value, key) => {
headerMap[key.toLowerCase()] = value;
});
this.headerMap = headerMap;
}
public get headers(): Readonly<Record<string, string>> {
return this.headerMap;
}
public get traceId(): string | undefined {
return this.headerMap["x-trace-id"] ?? this.headerMap["x-request-id"];
}
}
export type QueryPrimitive = string | number | boolean;
export type QueryValue = QueryPrimitive | QueryPrimitive[] | null | undefined;
export type Query = Record<string, QueryValue>;
export type PathParams = Record<string, string | number | boolean>;
export type NextFetchOptions = {
revalidate?: number | false;
tags?: string[];
};
export type RequestOptions = {
method?: HttpMethod;
pathParams?: PathParams;
query?: Query;
json?: unknown;
rawBody?: BodyInit;
form?: FormData;
headers?: HeadersInit;
timeoutMs?: number;
expectText?: boolean;
expectBinary?: boolean;
cache?: RequestCache;
next?: NextFetchOptions;
/**
* 401 기본 처리를 실행하지 않는다.
*/
skipUnauthorizedHandler?: boolean;
/**
* 403 기본 처리를 실행하지 않는다.
*/
skipForbiddenHandler?: boolean;
/**
* 401·403 이외의 오류에 대한 기본 처리를 실행하지 않는다.
*/
skipResponseErrorHandler?: boolean;
/**
* @deprecated
* skipUnauthorizedHandler와 skipForbiddenHandler를 사용한다.
*/
skipAuthErrorHandler?: boolean;
};
export type HttpClientOptions = {
getToken?: () => string | null | undefined;
defaultTimeoutMs?: number;
defaultHeaders?: HeadersInit;
/**
* 401 처리.
*
* undefined:
* 기본 로그아웃 처리
*
* 함수:
* 전달한 함수로 대체
*
* false:
* 전역 401 처리 비활성화
*/
onUnauthorized?: HttpErrorHandler | false;
/**
* 403 처리.
*
* undefined:
* 기본 로그아웃 처리
*
* 함수:
* 전달한 함수로 대체
*
* false:
* 전역 403 처리 비활성화
*/
onForbidden?: HttpErrorHandler | false;
/**
* 401·403 이외의 HTTP 오류 처리.
*
* undefined:
* 기본 오류 메시지 표시
*
* 함수:
* 전달한 함수로 대체
*
* false:
* 전역 오류 표시 비활성화
*/
onResponseError?: HttpErrorHandler | false;
/**
* @deprecated
* onUnauthorized와 onForbidden을 사용한다.
*
* 두 옵션이 별도로 지정되지 않았을 때
* 401과 403 모두에 적용된다.
*/
onAuthError?: HttpErrorHandler | false;
logoutPath?: string;
authExcludedPaths?: string[];
resolveErrorMessage?: ErrorMessageResolver;
notifyError?: ErrorNotifier;
};
type RequestFactoryOptions = {
getToken: (() => string | null | undefined) | undefined;
defaultTimeoutMs: number;
defaultHeaders: HeadersInit;
onUnauthorized: HttpErrorHandler | undefined;
onForbidden: HttpErrorHandler | undefined;
onResponseError: HttpErrorHandler | undefined;
};
type NextRequestInit = RequestInit & {
next?: NextFetchOptions;
};
type RequestOptionBodyKeys = "method" | "json" | "rawBody" | "form";
export type RequestOptionsWithoutBody = Omit<
RequestOptions,
RequestOptionBodyKeys
>;
export type DeleteRequestOptions = Omit<RequestOptions, "method">;
const replacePathParams = (path: string, params?: PathParams): string => {
if (!params) {
return path;
}
let result = path;
for (const [key, value] of Object.entries(params)) {
result = result.replaceAll(`:${key}`, encodeURIComponent(String(value)));
}
return result;
};
const createBaseUrl = (baseUrl: string): URL => {
const result = new URL(baseUrl);
if (!result.pathname.endsWith("/")) {
result.pathname = `${result.pathname}/`;
}
return result;
};
const buildUrl = (
baseUrl: string,
path: string,
options: RequestOptions,
): URL => {
const replacedPath = replacePathParams(path, options.pathParams);
if (/^https?:\/\//i.test(replacedPath)) {
return new URL(replacedPath);
}
const normalizedPath = replacedPath.replace(/^\/+/, "");
return new URL(normalizedPath, createBaseUrl(baseUrl));
};
const appendQuery = (url: URL, query?: Query): void => {
if (!query) {
return;
}
for (const [key, value] of Object.entries(query)) {
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
for (const item of value) {
url.searchParams.append(key, String(item));
}
continue;
}
url.searchParams.set(key, String(value));
}
};
const buildHeaders = (
defaultHeaders: HeadersInit,
getToken: (() => string | null | undefined) | undefined,
requestHeaders?: HeadersInit,
): Headers => {
const headers = new Headers(defaultHeaders);
const token = getToken?.();
if (token) {
headers.set("authorization", `Bearer ${token}`);
}
if (requestHeaders) {
const overrides = new Headers(requestHeaders);
overrides.forEach((value, key) => {
headers.set(key, value);
});
}
return headers;
};
const buildBody = (
options: RequestOptions,
headers: Headers,
): BodyInit | undefined => {
if (options.form !== undefined) {
/*
* FormData의 Content-Type과 boundary는
* fetch가 자동으로 생성해야 한다.
*/
headers.delete("content-type");
return options.form;
}
if (options.rawBody !== undefined) {
return options.rawBody;
}
if (options.json === undefined) {
return undefined;
}
if (!headers.has("content-type")) {
headers.set("content-type", "application/json");
}
return typeof options.json === "string"
? options.json
: JSON.stringify(options.json);
};
const isJsonContentType = (contentType: string): boolean => {
const normalized = contentType.toLowerCase();
return (
normalized.includes("application/json") || normalized.includes("+json")
);
};
const parseSuccessBody = (
rawText: string,
contentType: string,
expectText: boolean,
): unknown => {
if (expectText) {
return rawText;
}
if (!rawText) {
return null;
}
if (!isJsonContentType(contentType)) {
return rawText;
}
return JSON.parse(rawText);
};
const parseErrorBody = (rawText: string, contentType: string): unknown => {
if (!rawText) {
return null;
}
if (!isJsonContentType(contentType)) {
return rawText;
}
try {
return JSON.parse(rawText);
} catch {
return rawText;
}
};
const isAbortError = (error: unknown): boolean => {
if (typeof error !== "object" || error === null) {
return false;
}
const candidate = error as {
name?: unknown;
code?: unknown;
message?: unknown;
};
if (candidate.name === "AbortError" || candidate.code === "ABORT_ERR") {
return true;
}
return (
typeof candidate.message === "string" &&
candidate.message.toLowerCase().includes("aborted")
);
};
const extractErrorCode = (error: unknown): string | undefined => {
if (typeof error !== "object" || error === null) {
return undefined;
}
const candidate = error as {
code?: unknown;
cause?: unknown;
};
if (typeof candidate.cause === "object" && candidate.cause !== null) {
const cause = candidate.cause as {
code?: unknown;
};
if (typeof cause.code === "string") {
return cause.code;
}
}
return typeof candidate.code === "string" ? candidate.code : undefined;
};
const processHttpError = (
error: HttpError,
requestOptions: RequestOptions,
clientOptions: RequestFactoryOptions,
): never => {
const skipAllAuthHandlers = requestOptions.skipAuthErrorHandler ?? false;
if (error.status === 401) {
if (!skipAllAuthHandlers && !requestOptions.skipUnauthorizedHandler) {
clientOptions.onUnauthorized?.(error);
}
throw error;
}
if (error.status === 403) {
if (!skipAllAuthHandlers && !requestOptions.skipForbiddenHandler) {
clientOptions.onForbidden?.(error);
}
throw error;
}
if (!requestOptions.skipResponseErrorHandler) {
clientOptions.onResponseError?.(error);
}
throw error;
};
const processErrorResponse = (
response: Response,
data: unknown,
url: URL,
requestOptions: RequestOptions,
clientOptions: RequestFactoryOptions,
): never => {
const error = new HttpError(
response.status,
data,
url.toString(),
response.headers,
);
return processHttpError(error, requestOptions, clientOptions);
};
const resolveAuthHandler = (
specificHandler: HttpErrorHandler | false | undefined,
legacyHandler: HttpErrorHandler | false | undefined,
defaultHandler: HttpErrorHandler,
): HttpErrorHandler | undefined => {
if (specificHandler === false) {
return undefined;
}
if (typeof specificHandler === "function") {
return specificHandler;
}
if (legacyHandler === false) {
return undefined;
}
if (typeof legacyHandler === "function") {
return legacyHandler;
}
return defaultHandler;
};
const resolveResponseHandler = (
options: HttpClientOptions,
): HttpErrorHandler | undefined => {
if (options.onResponseError === false) {
return undefined;
}
if (typeof options.onResponseError === "function") {
return options.onResponseError;
}
return (error: HttpError): void => {
showErrorMessage(error, options);
};
};
const createResolvedOptions = (
options: HttpClientOptions,
): RequestFactoryOptions => {
const logoutPath = options.logoutPath ?? "/logout";
const authExcludedPaths = options.authExcludedPaths ?? ["/login", logoutPath];
const defaultLogoutHandler: HttpErrorHandler = () => {
redirectToLogout({
logoutPath,
excludedPaths: authExcludedPaths,
});
};
return {
getToken: options.getToken,
defaultTimeoutMs: options.defaultTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,
defaultHeaders: options.defaultHeaders ?? {
"content-type": "application/json",
},
onUnauthorized: resolveAuthHandler(
options.onUnauthorized,
options.onAuthError,
defaultLogoutHandler,
),
onForbidden: resolveAuthHandler(
options.onForbidden,
options.onAuthError,
defaultLogoutHandler,
),
onResponseError: resolveResponseHandler(options),
};
};
const createRequest = (
baseUrl: string,
clientOptions: RequestFactoryOptions,
) => {
return async <T = unknown>(
path: string,
options: RequestOptions = {},
): Promise<T> => {
const url = buildUrl(baseUrl, path, options);
appendQuery(url, options.query);
const headers = buildHeaders(
clientOptions.defaultHeaders,
clientOptions.getToken,
options.headers,
);
const body = buildBody(options, headers);
const controller = new AbortController();
const timeoutMs = options.timeoutMs ?? clientOptions.defaultTimeoutMs;
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
const isServer = typeof window === "undefined";
const cache =
options.cache ?? (isServer && options.next ? "force-cache" : "no-store");
const init: NextRequestInit = {
method: options.method ?? (body === undefined ? "GET" : "POST"),
headers,
signal: controller.signal,
cache,
};
if (body !== undefined) {
init.body = body;
}
if (isServer && options.next !== undefined) {
init.next = options.next;
}
try {
const response = await fetch(url.toString(), init);
if (options.expectBinary) {
if (!response.ok) {
const rawText = await response.text().catch(() => "");
const contentType = response.headers.get("content-type") ?? "";
const errorData = parseErrorBody(rawText, contentType);
processErrorResponse(
response,
errorData,
url,
options,
clientOptions,
);
}
return (await response.arrayBuffer()) as T;
}
const contentType = response.headers.get("content-type") ?? "";
const rawText = await response.text().catch(() => "");
if (!response.ok) {
const errorData = parseErrorBody(rawText, contentType);
processErrorResponse(response, errorData, url, options, clientOptions);
}
const parsed = parseSuccessBody(
rawText,
contentType,
options.expectText ?? false,
);
return parsed as T;
} catch (error: unknown) {
if (error instanceof HttpError) {
throw error;
}
if (isAbortError(error)) {
return processHttpError(
new HttpError(
408,
{
message: "요청 시간이 초과되었습니다.",
timeoutMs,
},
url.toString(),
),
options,
clientOptions,
);
}
if (extractErrorCode(error) === "ECONNREFUSED") {
return processHttpError(
new HttpError(
503,
{
message: "백엔드 서버에 연결할 수 없습니다.",
},
url.toString(),
),
options,
clientOptions,
);
}
return processHttpError(
new HttpError(
0,
{
message: "네트워크 요청을 처리하지 못했습니다.",
cause: error,
},
url.toString(),
),
options,
clientOptions,
);
} finally {
clearTimeout(timeoutId);
}
};
};
export const createHttpClient = (
baseUrl: string,
options: HttpClientOptions = {},
) => {
const request = createRequest(baseUrl, createResolvedOptions(options));
const get = <T = unknown>(
path: string,
requestOptions?: RequestOptionsWithoutBody,
): Promise<T> => {
return request<T>(path, {
...(requestOptions ?? {}),
method: "GET",
});
};
const post = <T = unknown>(
path: string,
json?: unknown,
requestOptions?: RequestOptionsWithoutBody,
): Promise<T> => {
return request<T>(path, {
...(requestOptions ?? {}),
method: "POST",
json,
});
};
const put = <T = unknown>(
path: string,
json?: unknown,
requestOptions?: RequestOptionsWithoutBody,
): Promise<T> => {
return request<T>(path, {
...(requestOptions ?? {}),
method: "PUT",
json,
});
};
const patch = <T = unknown>(
path: string,
json?: unknown,
requestOptions?: RequestOptionsWithoutBody,
): Promise<T> => {
return request<T>(path, {
...(requestOptions ?? {}),
method: "PATCH",
json,
});
};
const del = <T = unknown>(
path: string,
requestOptions?: DeleteRequestOptions,
): Promise<T> => {
return request<T>(path, {
...(requestOptions ?? {}),
method: "DELETE",
});
};
const postForm = <T = unknown>(
path: string,
form: FormData,
requestOptions?: RequestOptionsWithoutBody,
): Promise<T> => {
return request<T>(path, {
...(requestOptions ?? {}),
method: "POST",
form,
});
};
const putForm = <T = unknown>(
path: string,
form: FormData,
requestOptions?: RequestOptionsWithoutBody,
): Promise<T> => {
return request<T>(path, {
...(requestOptions ?? {}),
method: "PUT",
form,
});
};
return {
request,
get,
post,
put,
patch,
del,
postForm,
putForm,
};
};
export type HttpClient = ReturnType<typeof createHttpClient>;

92
src/http/http-util.ts Normal file
View File

@@ -0,0 +1,92 @@
import { HttpError } from "./http-client.js";
import { getServerMessage } from "./error-policy.js";
export const UNKNOWN_HTTP_ERROR = "UNKNOWN_HTTP_ERROR";
export const NONE_HTTP_ERROR = "NONE_HTTP_ERROR";
export type ApiError = {
status: number;
code: string;
message: string;
};
export type ApiErrorOptions = {
fallbackMessage?: string;
debug?: boolean;
};
export const apiError = (
error: unknown,
options: ApiErrorOptions = {},
): ApiError => {
const { fallbackMessage = "요청 처리에 실패했습니다.", debug = false } =
options;
if (error instanceof HttpError) {
const data = error.data as {
code?: unknown;
detail?: unknown;
message?: unknown;
errMessage?: unknown;
} | null;
const code =
typeof data?.code === "string" ? data.code : UNKNOWN_HTTP_ERROR;
const message =
(typeof data?.detail === "string" && data.detail) ||
getServerMessage(error.data) ||
(typeof data?.errMessage === "string" && data.errMessage) ||
`HTTP ${error.status}`;
if (debug) {
console.groupCollapsed(`[API ERROR] ${error.status} / ${code}`);
console.log("url:", error.url);
if (error.traceId) {
console.log("traceId:", error.traceId);
}
console.log("raw data:", error.data);
console.groupEnd();
}
return {
status: error.status,
code,
message,
};
}
if (debug) {
console.error("[NON-HTTP ERROR]", error);
}
return {
status: 500,
code: NONE_HTTP_ERROR,
message: fallbackMessage,
};
};
export const errorToResponse = (error: unknown): Response => {
if (error instanceof HttpError) {
const payload = error.data ?? {
message: "서버에서 오류 응답을 받았습니다.",
};
return Response.json(payload, {
status: error.status,
});
}
return Response.json(
{
message: "서버 내부 오류가 발생했습니다.",
},
{
status: 500,
},
);
};

4
src/http/index.ts Normal file
View File

@@ -0,0 +1,4 @@
// src/http/index.ts
export * from "./http-client.js";
export * from "./error-policy.js";
export * from "./http-util.js";