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

View File

@@ -0,0 +1,75 @@
export const XLSX_MIME_TYPE =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
export const DEFAULT_BINARY_MIME_TYPE = "application/octet-stream";
const assertBrowserEnvironment = (): void => {
if (typeof window === "undefined" || typeof document === "undefined") {
throw new Error(
"파일 다운로드 기능은 브라우저 환경에서만 사용할 수 있습니다.",
);
}
};
const stripBase64Prefix = (value: string): string => {
const commaIndex = value.indexOf(",");
if (value.startsWith("data:") && commaIndex >= 0) {
return value.slice(commaIndex + 1);
}
return value;
};
export const base64ToBlob = (
base64: string,
contentType = DEFAULT_BINARY_MIME_TYPE,
): Blob => {
assertBrowserEnvironment();
const normalizedBase64 = stripBase64Prefix(base64);
const byteString = window.atob(normalizedBase64);
const bytes = new Uint8Array(byteString.length);
for (let index = 0; index < byteString.length; index += 1) {
bytes[index] = byteString.charCodeAt(index);
}
return new Blob([bytes], { type: contentType });
};
export const downloadFile = (blob: Blob, filename: string): void => {
assertBrowserEnvironment();
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = objectUrl;
anchor.download = filename;
anchor.style.display = "none";
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
/*
* 클릭 직후 바로 해제하면 일부 브라우저에서
* 다운로드가 취소될 가능성이 있어 다음 tick에서 해제한다.
*/
window.setTimeout(() => {
URL.revokeObjectURL(objectUrl);
}, 0);
};
export const downloadBase64File = (
base64: string,
filename: string,
contentType = DEFAULT_BINARY_MIME_TYPE,
): void => {
const blob = base64ToBlob(base64, contentType);
downloadFile(blob, filename);
};

1
src/browser/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from "./file-download.js";

207
src/config/env.ts Normal file
View File

@@ -0,0 +1,207 @@
export type EnvInput = string | null | undefined;
export type EnvStringOptions = {
/**
* 앞뒤 공백을 제거할지 여부
*
* @default true
*/
trim?: boolean;
/**
* 빈 문자열을 유효한 값으로 허용할지 여부
*
* @default false
*/
allowEmpty?: boolean;
};
export type NumberEnvOptions = EnvStringOptions & {
min?: number;
max?: number;
};
export type BooleanEnvOptions = EnvStringOptions & {
trueValues?: readonly string[];
falseValues?: readonly string[];
};
export class EnvValidationError extends Error {
readonly variableName: string;
readonly reason: string;
constructor(variableName: string, reason: string) {
super(`Invalid environment variable "${variableName}": ${reason}`);
this.name = "EnvValidationError";
this.variableName = variableName;
this.reason = reason;
}
}
const normalizeEnvValue = (
value: EnvInput,
trim: boolean,
): string | undefined => {
if (value === undefined || value === null) {
return undefined;
}
return trim ? value.trim() : value;
};
export const requiredEnv = (
variableName: string,
value: EnvInput,
options: EnvStringOptions = {},
): string => {
const { trim = true, allowEmpty = false } = options;
const normalized = normalizeEnvValue(value, trim);
if (normalized === undefined) {
throw new EnvValidationError(variableName, "required value is missing");
}
if (!allowEmpty && normalized.length === 0) {
throw new EnvValidationError(variableName, "empty value is not allowed");
}
return normalized;
};
export const optionalEnv = (
variableName: string,
value: EnvInput,
options: EnvStringOptions = {},
): string | undefined => {
const { trim = true, allowEmpty = false } = options;
const normalized = normalizeEnvValue(value, trim);
if (normalized === undefined) {
return undefined;
}
if (!allowEmpty && normalized.length === 0) {
return undefined;
}
return normalized;
};
export const enumEnv = <const TAllowed extends readonly string[]>(
variableName: string,
value: EnvInput,
allowedValues: TAllowed,
options: EnvStringOptions = {},
): TAllowed[number] => {
const normalized = requiredEnv(variableName, value, options);
const matched = allowedValues.some((allowedValue) => {
return allowedValue === normalized;
});
if (!matched) {
throw new EnvValidationError(
variableName,
[
`received "${normalized}"`,
`allowed values: ${allowedValues.join(", ")}`,
].join("; "),
);
}
return normalized as TAllowed[number];
};
export const booleanEnv = (
variableName: string,
value: EnvInput,
options: BooleanEnvOptions = {},
): boolean => {
const {
trueValues = ["true", "1", "yes", "on"],
falseValues = ["false", "0", "no", "off"],
} = options;
const normalized = requiredEnv(variableName, value, options).toLowerCase();
if (trueValues.some((item) => item.toLowerCase() === normalized)) {
return true;
}
if (falseValues.some((item) => item.toLowerCase() === normalized)) {
return false;
}
throw new EnvValidationError(
variableName,
`cannot convert "${normalized}" to boolean`,
);
};
export const numberEnv = (
variableName: string,
value: EnvInput,
options: NumberEnvOptions = {},
): number => {
const normalized = requiredEnv(variableName, value, options);
const parsed = Number(normalized);
if (!Number.isFinite(parsed)) {
throw new EnvValidationError(
variableName,
`cannot convert "${normalized}" to number`,
);
}
if (options.min !== undefined && parsed < options.min) {
throw new EnvValidationError(
variableName,
`must be greater than or equal to ${options.min}`,
);
}
if (options.max !== undefined && parsed > options.max) {
throw new EnvValidationError(
variableName,
`must be less than or equal to ${options.max}`,
);
}
return parsed;
};
export const integerEnv = (
variableName: string,
value: EnvInput,
options: NumberEnvOptions = {},
): number => {
const parsed = numberEnv(variableName, value, options);
if (!Number.isInteger(parsed)) {
throw new EnvValidationError(
variableName,
`must be an integer; received "${parsed}"`,
);
}
return parsed;
};
export const createEnv = <const TValues extends Record<string, unknown>>(
values: TValues,
): Readonly<TValues> => {
return Object.freeze(values);
};
export const env = Object.freeze({
required: requiredEnv,
optional: optionalEnv,
oneOf: enumEnv,
boolean: booleanEnv,
number: numberEnv,
integer: integerEnv,
});

2
src/config/index.ts Normal file
View File

@@ -0,0 +1,2 @@
export * from "./env.js";
export * from "./next-config.js";

14
src/config/next-config.ts Normal file
View File

@@ -0,0 +1,14 @@
export const createKriNextConfig = <TConfig extends object>(
config: TConfig,
) => {
return {
output: "standalone" as const,
reactCompiler: true as const,
/*
* 프로젝트 설정을 뒤에 병합해
* 필요한 경우 기본값을 덮어쓸 수 있다.
*/
...config,
};
};

View File

@@ -1,8 +1,5 @@
export type DateTimeFormatOption =
| "date"
| "dateHour"
| "dateHourMin"
| "dateTime";
"date" | "dateHour" | "dateHourMin" | "dateTime";
const KST_OFFSET_MS = 9 * 60 * 60 * 1000;
@@ -14,28 +11,20 @@ function pad2(value: number): string {
* 날짜 값을 한국 표준시(KST) 문자열로 변환한다.
*/
export function formatKst(
input: string | number | Date | null | undefined,
option: DateTimeFormatOption = "dateTime",
input: string | number | Date | null | undefined,
option: DateTimeFormatOption = "dateTime",
): string {
if (
input === null
|| input === undefined
|| input === ""
) {
if (input === null || input === undefined || input === "") {
return "";
}
const date = input instanceof Date
? input
: new Date(input);
const date = input instanceof Date ? input : new Date(input);
if (Number.isNaN(date.getTime())) {
return "";
}
const kstDate = new Date(
date.getTime() + KST_OFFSET_MS,
);
const kstDate = new Date(date.getTime() + KST_OFFSET_MS);
const year = kstDate.getUTCFullYear();
const month = pad2(kstDate.getUTCMonth() + 1);
@@ -59,4 +48,4 @@ export function formatKst(
case "dateTime":
return `${datePart} ${hour}:${minute}:${second}`;
}
}
}

97
src/hooks/create/auth.ts Normal file
View File

@@ -0,0 +1,97 @@
"use client";
import { atom, useAtom } from "jotai";
import { useCallback, useMemo } from "react";
export type EmptyAuthExtra = Record<never, never>;
export type AuthState<TUser, TExtra extends object = EmptyAuthExtra> = {
user: TUser | null;
} & TExtra;
export type AuthStateAction<TUser, TExtra extends object> =
| AuthState<TUser, TExtra>
| ((previous: AuthState<TUser, TExtra>) => AuthState<TUser, TExtra>);
export type CreateAuthHookOptions<TUser, TExtra extends object> = {
initialState: AuthState<TUser, TExtra>;
};
export const createAuthHook = <TUser, TExtra extends object = EmptyAuthExtra>(
options: CreateAuthHookOptions<TUser, TExtra>,
) => {
const createInitialState = (): AuthState<TUser, TExtra> => {
return {
...options.initialState,
};
};
const authAtom = atom<AuthState<TUser, TExtra>>(createInitialState());
const useAuth = () => {
const [auth, setAuthValue] = useAtom(authAtom);
const setAuth = useCallback(
(next: AuthStateAction<TUser, TExtra>): void => {
if (typeof next === "function") {
setAuthValue((previous) => {
return next(previous);
});
return;
}
setAuthValue(next);
},
[setAuthValue],
);
const patchAuth = useCallback(
(patch: Partial<AuthState<TUser, TExtra>>): void => {
setAuthValue((previous) => {
return {
...previous,
...patch,
};
});
},
[setAuthValue],
);
const setUser = useCallback(
(user: TUser | null): void => {
setAuthValue((previous) => {
return {
...previous,
user,
};
});
},
[setAuthValue],
);
const resetAuth = useCallback((): void => {
setAuthValue(createInitialState());
}, [setAuthValue]);
return useMemo(
() => ({
auth,
user: auth.user,
isAuthenticated: auth.user !== null,
setAuth,
patchAuth,
setUser,
resetAuth,
}),
[auth, patchAuth, resetAuth, setAuth, setUser],
);
};
return {
authAtom,
useAuth,
};
};

View File

@@ -0,0 +1,87 @@
"use client";
import { atom, useAtom } from "jotai";
import { useCallback } from "react";
export const createDialogHook = <TDialogId extends string>() => {
const openDialogIdsAtom = atom<TDialogId[]>([]);
const useDialog = () => {
const [openDialogIds, setOpenDialogIds] = useAtom(openDialogIdsAtom);
const openDialog = useCallback(
(dialogId: TDialogId): void => {
setOpenDialogIds((previous) => {
if (previous.includes(dialogId)) {
return previous;
}
return [...previous, dialogId];
});
},
[setOpenDialogIds],
);
const closeDialog = useCallback(
(dialogId: TDialogId): void => {
setOpenDialogIds((previous) => {
return previous.filter((id) => id !== dialogId);
});
},
[setOpenDialogIds],
);
const setDialogOpen = useCallback(
(dialogId: TDialogId, open: boolean): void => {
if (open) {
openDialog(dialogId);
return;
}
closeDialog(dialogId);
},
[closeDialog, openDialog],
);
const toggleDialog = useCallback(
(dialogId: TDialogId): void => {
setOpenDialogIds((previous) => {
if (previous.includes(dialogId)) {
return previous.filter((id) => id !== dialogId);
}
return [...previous, dialogId];
});
},
[setOpenDialogIds],
);
const closeAllDialogs = useCallback((): void => {
setOpenDialogIds([]);
}, [setOpenDialogIds]);
const isDialogOpen = useCallback(
(dialogId: TDialogId): boolean => {
return openDialogIds.includes(dialogId);
},
[openDialogIds],
);
return {
openDialogIds,
openDialog,
closeDialog,
setDialogOpen,
toggleDialog,
closeAllDialogs,
isDialogOpen,
};
};
return {
openDialogIdsAtom,
useDialog,
};
};

View File

@@ -0,0 +1,79 @@
"use client";
import { atom, useAtomValue, useSetAtom } from "jotai";
import { useCallback } from "react";
export const createLoadingHook = () => {
const loadingCountAtom = atom(0);
const isLoadingAtom = atom((get) => {
return get(loadingCountAtom) > 0;
});
const useLoading = () => {
const loadingCount = useAtomValue(loadingCountAtom);
const isLoading = useAtomValue(isLoadingAtom);
const setLoadingCount = useSetAtom(loadingCountAtom);
const showLoading = useCallback((): void => {
setLoadingCount((previous) => previous + 1);
}, [setLoadingCount]);
const hideLoading = useCallback((): void => {
setLoadingCount((previous) => Math.max(0, previous - 1));
}, [setLoadingCount]);
const resetLoading = useCallback((): void => {
setLoadingCount(0);
}, [setLoadingCount]);
const withLoading = useCallback(
function runWithLoading<T>(task: () => T): T {
showLoading();
try {
return task();
} finally {
hideLoading();
}
},
[hideLoading, showLoading],
);
const withLoadingAsync = useCallback(
async function runWithLoadingAsync<T>(
task: () => Promise<T>,
): Promise<T> {
showLoading();
try {
return await task();
} finally {
hideLoading();
}
},
[hideLoading, showLoading],
);
return {
loadingCount,
isLoading,
showLoading,
hideLoading,
resetLoading,
withLoading,
withLoadingAsync,
};
};
return {
loadingCountAtom,
isLoadingAtom,
useLoading,
};
};

View File

@@ -0,0 +1,68 @@
"use client";
import { useMemo } from "react";
export type StorageScope = "local" | "session";
export type StorageAdapter = {
get: (key: string) => unknown | null;
set: (key: string, value: unknown) => void;
remove: (key: string) => void;
};
type StorageKey<TSchema extends object> = Extract<keyof TSchema, string>;
export type StorageHandle<TValue> = {
scope: StorageScope;
get: () => TValue | null;
set: (value: TValue) => void;
remove: () => void;
};
export type CreateStorageHookOptions<TSchema extends object> = {
resolveStorageScope: (key: StorageKey<TSchema>) => StorageScope;
localStorageAdapter: StorageAdapter;
sessionStorageAdapter: StorageAdapter;
};
export const createStorageHook = <TSchema extends object>(
options: CreateStorageHookOptions<TSchema>,
) => {
const useStorage = <TKey extends StorageKey<TSchema>>(
key: TKey,
): StorageHandle<TSchema[TKey]> => {
const scope = options.resolveStorageScope(key);
return useMemo(() => {
const adapter =
scope === "local"
? options.localStorageAdapter
: options.sessionStorageAdapter;
return {
scope,
get: () => {
return adapter.get(key) as TSchema[TKey] | null;
},
set: (value: TSchema[TKey]): void => {
adapter.set(key, value);
},
remove: (): void => {
adapter.remove(key);
},
};
}, [key, scope]);
};
return useStorage;
};

10
src/hooks/index.ts Normal file
View File

@@ -0,0 +1,10 @@
"use client";
export * from "./use/previous.js";
export * from "./use/debounced-value.js";
export * from "./use/mounted.js";
export * from "./create/auth.js";
export * from "./create/loading.js";
export * from "./create/storage.js";
export * from "./create/dialog.js";

View File

@@ -0,0 +1,22 @@
"use client";
import { useEffect, useState } from "react";
export const useDebouncedValue = <T>(value: T, delayMs = 300): T => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timeoutId = setTimeout(
() => {
setDebouncedValue(value);
},
Math.max(0, delayMs),
);
return () => {
clearTimeout(timeoutId);
};
}, [value, delayMs]);
return debouncedValue;
};

13
src/hooks/use/mounted.ts Normal file
View File

@@ -0,0 +1,13 @@
"use client";
import { useEffect, useState } from "react";
export const useMounted = (): boolean => {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
return mounted;
};

13
src/hooks/use/previous.ts Normal file
View File

@@ -0,0 +1,13 @@
"use client";
import { useEffect, useRef } from "react";
export const usePrevious = <T>(value: T): T | undefined => {
const previousRef = useRef<T | undefined>(undefined);
useEffect(() => {
previousRef.current = value;
}, [value]);
return previousRef.current;
};

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";

View File

@@ -3,4 +3,4 @@ export type * from "./types.js";
export * from "./object.js";
export * from "./url.js";
export * from "./date.js";
export * from "./string.js";
export * from "./string.js";

View File

@@ -1,27 +1,21 @@
export function getKeyByValue<
const T extends Record<string, string>,
>(
map: T,
value: T[keyof T],
export function getKeyByValue<const T extends Record<string, string>>(
map: T,
value: T[keyof T],
): keyof T | undefined {
const entry = Object.entries(map).find(
([, currentValue]) => currentValue === value,
([, currentValue]) => currentValue === value,
);
return entry
? (entry[0] as keyof T)
: undefined;
return entry ? (entry[0] as keyof T) : undefined;
}
export function getNumberKeyByValue(
map: Record<number, string>,
value: string,
map: Record<number, string>,
value: string,
): number | undefined {
const entry = Object.entries(map).find(
([, currentValue]) => currentValue === value,
([, currentValue]) => currentValue === value,
);
return entry
? Number(entry[0])
: undefined;
}
return entry ? Number(entry[0]) : undefined;
}

5
src/query/index.ts Normal file
View File

@@ -0,0 +1,5 @@
"use client";
export * from "./query-client.js";
export * from "./query-provider.js";
export * from "./query-loading.js";

38
src/query/query-client.ts Normal file
View File

@@ -0,0 +1,38 @@
import { QueryClient, type QueryClientConfig } from "@tanstack/react-query";
export const DEFAULT_QUERY_RETRY_COUNT = 1;
export const DEFAULT_QUERY_STALE_TIME_MS = 30_000;
export const DEFAULT_QUERY_GC_TIME_MS = 5 * 60_000;
export const createQueryClient = (
config: QueryClientConfig = {},
): QueryClient => {
const defaultOptions = config.defaultOptions;
return new QueryClient({
...config,
defaultOptions: {
...defaultOptions,
queries: {
retry: DEFAULT_QUERY_RETRY_COUNT,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
staleTime: DEFAULT_QUERY_STALE_TIME_MS,
gcTime: DEFAULT_QUERY_GC_TIME_MS,
/*
* 프로젝트에서 전달한 설정을
* 공통 기본값보다 우선한다.
*/
...defaultOptions?.queries,
},
},
});
};

View File

@@ -0,0 +1,76 @@
"use client";
import { useIsFetching, useIsMutating } from "@tanstack/react-query";
import { useEffect } from "react";
export interface QueryLoadingMeta extends Record<string, unknown> {
/**
* true이면 해당 Query 또는 Mutation을
* 전역 Loading에서 제외한다.
*/
ignoreGlobalLoading?: boolean;
}
/**
* useQuery와 useMutation의 meta 타입을
* 동일하게 적용한다.
*/
declare module "@tanstack/react-query" {
interface Register {
queryMeta: QueryLoadingMeta;
mutationMeta: QueryLoadingMeta;
}
}
const shouldTrackGlobalLoading = (
meta: QueryLoadingMeta | undefined,
): boolean => {
return meta?.ignoreGlobalLoading !== true;
};
export type QueryLoadingState = {
fetchingCount: number;
mutatingCount: number;
totalCount: number;
isLoading: boolean;
};
export const useQueryLoading = (): QueryLoadingState => {
const fetchingCount = useIsFetching({
predicate: (query) => {
return shouldTrackGlobalLoading(query.options.meta);
},
});
const mutatingCount = useIsMutating({
predicate: (mutation) => {
return shouldTrackGlobalLoading(mutation.options.meta);
},
});
const totalCount = fetchingCount + mutatingCount;
return {
fetchingCount,
mutatingCount,
totalCount,
isLoading: totalCount > 0,
};
};
export type QueryLoadingSyncProps = {
onLoadingChange: (isLoading: boolean) => void;
};
export const QueryLoadingSync = ({
onLoadingChange,
}: QueryLoadingSyncProps) => {
const { isLoading } = useQueryLoading();
useEffect(() => {
onLoadingChange(isLoading);
}, [isLoading, onLoadingChange]);
return null;
};

View File

@@ -0,0 +1,39 @@
"use client";
import {
QueryClientProvider,
type QueryClient,
type QueryClientConfig,
} from "@tanstack/react-query";
import { useState, type ReactNode } from "react";
import { createQueryClient } from "./query-client.js";
export type QueryProviderProps = {
children: ReactNode;
/**
* 외부에서 생성한 QueryClient를
* 직접 전달할 때 사용한다.
*/
client?: QueryClient;
/**
* 내부 QueryClient 생성 설정이다.
* 최초 생성 시에만 사용한다.
*/
clientConfig?: QueryClientConfig;
};
export const QueryProvider = ({
children,
client: providedClient,
clientConfig,
}: QueryProviderProps) => {
const [client] = useState(() => {
return providedClient ?? createQueryClient(clientConfig);
});
return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
};

1
src/security/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from "./security.js";

315
src/security/security.ts Normal file
View File

@@ -0,0 +1,315 @@
import CryptoJS from "crypto-js";
export type WordArray = CryptoJS.lib.WordArray;
export type SecurityConfigError = {
message: string;
keyBytes: number;
ivBytes: number;
validKeyBytes: readonly number[];
requiredIvBytes: number;
};
export type SecurityDecryptError = {
error: unknown;
inputPreview: string;
};
export type CreateSecurityOptions = {
/**
* 기존 문자열을 그대로 UTF-8 WordArray로 변환한다.
*/
key: string;
/**
* 기존 문자열을 그대로 UTF-8 WordArray로 변환한다.
*/
iv: string;
onInvalidConfig?: (error: SecurityConfigError) => void;
onDecryptError?: (error: SecurityDecryptError) => void;
};
const VALID_AES_KEY_BYTES = [16, 24, 32] as const;
const AES_IV_BYTES = 16;
const createConfigError = (
keyBytes: number,
ivBytes: number,
): SecurityConfigError => {
const message = [
"AES 설정이 올바르지 않습니다.",
`KEY: ${keyBytes} bytes (허용: ${VALID_AES_KEY_BYTES.join(", ")})`,
`IV: ${ivBytes} bytes (필수: ${AES_IV_BYTES})`,
].join("\n");
return {
message,
keyBytes,
ivBytes,
validKeyBytes: VALID_AES_KEY_BYTES,
requiredIvBytes: AES_IV_BYTES,
};
};
export const createSecurity = (options: CreateSecurityOptions) => {
const key = CryptoJS.enc.Utf8.parse(options.key);
const iv = CryptoJS.enc.Utf8.parse(options.iv);
const validKey = VALID_AES_KEY_BYTES.includes(key.sigBytes as 16 | 24 | 32);
const validIv = iv.sigBytes === AES_IV_BYTES;
if (!validKey || !validIv) {
const configError = createConfigError(key.sigBytes, iv.sigBytes);
options.onInvalidConfig?.(configError);
throw new Error(configError.message);
}
const encodeUtf8 = (input: WordArray): string => {
return CryptoJS.enc.Utf8.stringify(input);
};
const decodeUtf8 = (input: string): WordArray => {
return CryptoJS.enc.Utf8.parse(input);
};
const encodeHex = (input: WordArray): string => {
return CryptoJS.enc.Hex.stringify(input);
};
const decodeHex = (input: string): WordArray => {
return CryptoJS.enc.Hex.parse(input);
};
const hasSpecialChars = (input: string): boolean => {
return input.includes("\u200b") || input.includes("\u200c");
};
const convertFromSpecialChars = (input: string): string => {
return input
.split("ㅤ")
.map((binary) => {
return binary.replace(/\u200b/g, "0").replace(/\u200c/g, "1");
})
.map((binary) => {
return String.fromCharCode(Number.parseInt(binary, 2));
})
.join("");
};
const encodeBase64 = (input: WordArray): string => {
return CryptoJS.enc.Base64.stringify(input);
};
const decodeBase64 = (input: string): WordArray => {
const normalized = hasSpecialChars(input)
? convertFromSpecialChars(input)
: input;
return CryptoJS.enc.Base64.parse(normalized);
};
const encodeBase64Url = (input: WordArray): string => {
return CryptoJS.enc.Base64url.stringify(input);
};
const decodeBase64Url = (input: string): WordArray => {
const normalized = hasSpecialChars(input)
? convertFromSpecialChars(input)
: input;
return CryptoJS.enc.Base64url.parse(normalized);
};
const encodeBase64Utf8 = (input: string): string => {
return encodeBase64(decodeUtf8(input));
};
const decodeBase64Utf8 = (input: string): string => {
return encodeUtf8(decodeBase64(input));
};
const encodeBase64UrlUtf8 = (input: string): string => {
return encodeBase64Url(decodeUtf8(input));
};
const decodeBase64UrlUtf8 = (input: string): string => {
return encodeUtf8(decodeBase64Url(input));
};
const encrypt = (input: WordArray): WordArray => {
const encrypted = CryptoJS.AES.encrypt(input, key, {
iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
});
return encrypted.ciphertext;
};
const decrypt = (input: WordArray): WordArray => {
const cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: input,
});
return CryptoJS.AES.decrypt(cipherParams, key, {
iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
});
};
const encryptBase64 = (input: string): string => {
return encodeBase64(encrypt(decodeUtf8(input)));
};
const decryptBase64 = (input: string): string => {
try {
return encodeUtf8(decrypt(decodeBase64(input)));
} catch (error: unknown) {
const inputPreview = `${input?.substring(0, 50) ?? ""}...`;
if (options.onDecryptError) {
options.onDecryptError({
error,
inputPreview,
});
} else {
console.error("Security.decryptBase64 오류:", {
input: inputPreview,
error: error instanceof Error ? error.message : String(error),
});
}
throw error;
}
};
const encryptBase64Url = (input: string): string => {
return encodeBase64Url(encrypt(decodeUtf8(input)));
};
const decryptBase64Url = (input: string): string => {
return encodeUtf8(decrypt(decodeBase64Url(input)));
};
const encryptBase64Object = (input: unknown): string => {
return encryptBase64(JSON.stringify(input));
};
const decryptBase64Object = <T = unknown>(input: string): T => {
return JSON.parse(decryptBase64(input)) as T;
};
const encryptBase64UrlObject = (input: unknown): string => {
return encryptBase64Url(JSON.stringify(input));
};
const decryptBase64UrlObject = <T = unknown>(input: string): T => {
return JSON.parse(decryptBase64Url(input)) as T;
};
const convertUint8ArrayToWordArray = (input: Uint8Array): WordArray => {
const words: number[] = [];
for (let index = 0; index < input.length; index += 1) {
const wordIndex = index >>> 2;
const bitOffset = 24 - (index % 4) * 8;
words[wordIndex] = (words[wordIndex] ?? 0) | (input[index]! << bitOffset);
}
return CryptoJS.lib.WordArray.create(words, input.length);
};
const convertWordArrayToUint8Array = (input: WordArray): Uint8Array => {
const bytes = new Uint8Array(input.sigBytes);
for (let index = 0; index < input.sigBytes; index += 1) {
const word = input.words[index >>> 2] ?? 0;
const bitOffset = 24 - (index % 4) * 8;
bytes[index] = (word >>> bitOffset) & 0xff;
}
return bytes;
};
const computeSha256 = (input: WordArray): WordArray => {
return CryptoJS.SHA256(input);
};
const computeSha256Hex = (input: WordArray): string => {
return encodeHex(computeSha256(input));
};
const computeHmacSha256 = (
input: WordArray,
hmacKey: WordArray,
): WordArray => {
return CryptoJS.HmacSHA256(input, hmacKey);
};
const computeHmacSha256Hex = (
input: WordArray,
hmacKey: WordArray,
): string => {
return encodeHex(computeHmacSha256(input, hmacKey));
};
return Object.freeze({
encryptBase64UrlObject,
decryptBase64UrlObject,
encryptBase64Object,
decryptBase64Object,
encryptBase64Url,
decryptBase64Url,
encryptBase64,
decryptBase64,
encrypt,
decrypt,
convertUint8ArrayToWordArray,
convertWordArrayToUint8Array,
computeHmacSha256Hex,
computeHmacSha256,
computeSha256Hex,
computeSha256,
encodeBase64UrlUtf8,
decodeBase64UrlUtf8,
encodeBase64Url,
decodeBase64Url,
encodeBase64Utf8,
decodeBase64Utf8,
encodeBase64,
decodeBase64,
encodeHex,
decodeHex,
encodeUtf8,
decodeUtf8,
});
};
export type SecurityApi = ReturnType<typeof createSecurity>;

57
src/server/client-ip.ts Normal file
View File

@@ -0,0 +1,57 @@
export type HeaderReader = Pick<Headers, "get">;
export type RequestWithHeaders = {
headers: HeaderReader;
};
export type ClientIpSource = HeaderReader | RequestWithHeaders;
const resolveHeaders = (source: ClientIpSource): HeaderReader => {
return "headers" in source ? source.headers : source;
};
/**
* 신뢰할 수 있는 리버스 프록시가 전달한 헤더에서
* 클라이언트 IP를 추출한다.
*
* x-forwarded-for는 첫 번째 값을 사용한다.
*/
export const getClientIp = (source: ClientIpSource): string | null => {
const headers = resolveHeaders(source);
const forwardedFor = headers.get("x-forwarded-for");
if (forwardedFor) {
const firstAddress = forwardedFor.split(",")[0]?.trim();
if (firstAddress) {
return firstAddress;
}
}
const realIp = headers.get("x-real-ip")?.trim();
if (realIp) {
return realIp;
}
const cloudflareIp = headers.get("cf-connecting-ip")?.trim();
if (cloudflareIp) {
return cloudflareIp;
}
const forwarded = headers.get("forwarded");
if (forwarded) {
const matched = forwarded.match(/for="?([^;,\s"]+)"?/i);
const forwardedIp = matched?.[1]?.trim();
if (forwardedIp) {
return forwardedIp;
}
}
return null;
};

1
src/server/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from "./client-ip.js";

View File

@@ -1,19 +1,13 @@
/**
* 문자열이 null, undefined 또는 공백인지 확인한다.
*/
export function isBlank(
value: string | null | undefined,
): boolean {
return value === null
|| value === undefined
|| value.trim().length === 0;
export function isBlank(value: string | null | undefined): boolean {
return value === null || value === undefined || value.trim().length === 0;
}
/**
* 문자열에 공백이 아닌 문자가 있는지 확인한다.
*/
export function isNotBlank(
value: string | null | undefined,
): boolean {
export function isNotBlank(value: string | null | undefined): boolean {
return !isBlank(value);
}
}

View File

@@ -1,9 +1,5 @@
export type ValueOf<T> = T[keyof T];
export type EnumLikeKey<
T extends Record<string, unknown>,
> = keyof T;
export type EnumLikeKey<T extends Record<string, unknown>> = keyof T;
export type EnumLikeValue<
T extends Record<string, unknown>,
> = ValueOf<T>;
export type EnumLikeValue<T extends Record<string, unknown>> = ValueOf<T>;

13
src/ui/class-name.ts Normal file
View File

@@ -0,0 +1,13 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/**
* 조건부 className을 결합하고
* 충돌하는 Tailwind CSS 클래스를 정리한다.
*/
export const cn = (...inputs: ClassValue[]): string => {
return twMerge(clsx(inputs));
};
export type { ClassValue };

1
src/ui/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from "./class-name.js";

View File

@@ -1,15 +1,11 @@
export type QueryParameterValue =
| string
| string[]
| undefined;
export type QueryParameterValue = string | string[] | undefined;
export type QueryParameters =
Record<string, QueryParameterValue>;
export type QueryParameters = Record<string, QueryParameterValue>;
export function buildUrlWithParams(
targetPath: string,
parameters: QueryParameters,
extra?: Record<string, string | undefined>,
targetPath: string,
parameters: QueryParameters,
extra?: Record<string, string | undefined>,
): string {
const searchParams = new URLSearchParams();
@@ -33,7 +29,5 @@ export function buildUrlWithParams(
const queryString = searchParams.toString();
return queryString
? `${targetPath}?${queryString}`
: targetPath;
}
return queryString ? `${targetPath}?${queryString}` : targetPath;
}