260615_01_FST: First Commit
This commit is contained in:
15
src/lib/env.client.ts
Normal file
15
src/lib/env.client.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
const required = <K extends keyof typeof RAW_PUBLIC_ENV>(name: K) => {
|
||||
const v = RAW_PUBLIC_ENV[name];
|
||||
if (!v) throw new Error(`Missing env: ${name}`);
|
||||
return v;
|
||||
};
|
||||
|
||||
const RAW_PUBLIC_ENV = {
|
||||
NEXT_PUBLIC_ENV: process.env.NEXT_PUBLIC_ENV,
|
||||
NEXT_PUBLIC_API_BASE: process.env.NEXT_PUBLIC_API_BASE,
|
||||
} as const;
|
||||
|
||||
export const clientEnv = {
|
||||
ENV: required("NEXT_PUBLIC_ENV"),
|
||||
API_BASE: required("NEXT_PUBLIC_API_BASE"),
|
||||
};
|
||||
10
src/lib/env.server.ts
Normal file
10
src/lib/env.server.ts
Normal 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 = {
|
||||
ENV: required("ENV"),
|
||||
API_BACK_SERVER: required("API_BACK_SERVER"),
|
||||
};
|
||||
0
src/lib/gwcf-util.ts
Normal file
0
src/lib/gwcf-util.ts
Normal file
307
src/lib/http-client.ts
Normal file
307
src/lib/http-client.ts
Normal file
@@ -0,0 +1,307 @@
|
||||
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<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())
|
||||
: {};
|
||||
}
|
||||
|
||||
get headers(): Record<string, string> {
|
||||
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<string, QueryValue>;
|
||||
export type PathParams = Record<string, string | number | boolean>;
|
||||
|
||||
export type NextFetchOptions = {
|
||||
revalidate?: number;
|
||||
tags?: string[];
|
||||
};
|
||||
|
||||
export type RequestOptions = {
|
||||
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;
|
||||
cache?: RequestCache; // "force-cache" | "no-store" | ...
|
||||
next?: NextFetchOptions; // Next 서버 fetch 확장 옵션
|
||||
};
|
||||
|
||||
export type HttpClientOptions = {
|
||||
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;
|
||||
};
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
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 <T = unknown>(path: string, options: RequestOptions = {}): Promise<T> => {
|
||||
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<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);
|
||||
|
||||
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.dispatchEvent(new CustomEvent("auth:expired"));
|
||||
} 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.dispatchEvent(new CustomEvent("auth:expired"));
|
||||
} 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 = <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);
|
||||
52
src/lib/http-util.ts
Normal file
52
src/lib/http-util.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import {NextResponse} from "next/server";
|
||||
import {HttpError} from "@/lib/http-client";
|
||||
import {clientEnv} from "@/lib/env.client";
|
||||
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "../const/common.const";
|
||||
|
||||
export type ApiError = {
|
||||
status: number
|
||||
code: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export const errorToResponse = (error: unknown) => {
|
||||
if (error instanceof HttpError) {
|
||||
const payload = error.data ?? { message: "서버에서 오류 응답을 받았습니다." }
|
||||
return NextResponse.json(payload, { status: error.status })
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ message: "서버 내부 오류가 발생했습니다." },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
const isDev = clientEnv.ENV !== "prod"
|
||||
|
||||
export const apiError = (e: unknown): ApiError => {
|
||||
if (e instanceof HttpError) {
|
||||
const d = e.data as any
|
||||
const code = typeof d?.code === "string" ? d.code : UNKNOWN_HTTP_ERROR
|
||||
const message =
|
||||
(typeof d?.detail === "string" && d.detail) ||
|
||||
(typeof d?.message === "string" && d.message) ||
|
||||
(typeof d?.errMessage === "string" && d.errMessage) ||
|
||||
(typeof d === "string" && d) ||
|
||||
`HTTP ${e.status}`
|
||||
|
||||
if (isDev) {
|
||||
console.groupCollapsed(
|
||||
`[API ERROR] ${e.status}${code ? ` / ${code}` : ""}`
|
||||
)
|
||||
console.log("url:", e.url)
|
||||
if (e.traceId) console.log("traceId:", e.traceId)
|
||||
console.log("raw data:", d)
|
||||
console.groupEnd()
|
||||
}
|
||||
|
||||
return { status: e.status, code, message }
|
||||
}
|
||||
|
||||
if (isDev) console.error("[NON-HTTP ERROR]", e)
|
||||
return { status: 500, code: NONE_HTTP_ERROR, message: "저장에 실패했습니다." }
|
||||
}
|
||||
223
src/lib/security.ts
Normal file
223
src/lib/security.ts
Normal file
@@ -0,0 +1,223 @@
|
||||
import CryptoJS from "crypto-js";
|
||||
|
||||
const KEY = CryptoJS.enc.Utf8.parse("kr!-Kfp@-fr0nT-CrypT0-Key-STR!!!");
|
||||
const IV = CryptoJS.enc.Utf8.parse("kr!-Kfp@Dash-IV!");
|
||||
const VALID_AES_KEY_BYTES = [16, 24, 32];
|
||||
const AES_IV_BYTES = 16;
|
||||
|
||||
const validateAesConfig = () => {
|
||||
const validKey = VALID_AES_KEY_BYTES.includes(KEY.sigBytes);
|
||||
const validIv = IV.sigBytes === AES_IV_BYTES;
|
||||
|
||||
if (validKey && validIv) return;
|
||||
|
||||
const message = [
|
||||
"AES 설정이 올바르지 않습니다.",
|
||||
`KEY: ${KEY.sigBytes} bytes (허용: ${VALID_AES_KEY_BYTES.join(", ")})`,
|
||||
`IV: ${IV.sigBytes} bytes (필수: ${AES_IV_BYTES})`,
|
||||
].join("\n");
|
||||
|
||||
if (typeof window !== "undefined" && process.env.NEXT_PUBLIC_ENV === "local") {
|
||||
const w = window as Window & { __kfpaCryptoConfigAlerted?: boolean };
|
||||
if (!w.__kfpaCryptoConfigAlerted) {
|
||||
w.__kfpaCryptoConfigAlerted = true;
|
||||
alert(message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
validateAesConfig();
|
||||
|
||||
export type WordArray = CryptoJS.lib.WordArray;
|
||||
|
||||
export class Security {
|
||||
public static encryptBase64UrlObject(input: unknown): string {
|
||||
const data = JSON.stringify(input);
|
||||
return this.encryptBase64Url(data);
|
||||
}
|
||||
|
||||
public static decryptBase64UrlObject(input: string): unknown {
|
||||
const data = this.decryptBase64Url(input);
|
||||
return JSON.parse(data);
|
||||
}
|
||||
|
||||
public static encryptBase64Object(input: unknown): string {
|
||||
const data = JSON.stringify(input);
|
||||
return this.encryptBase64(data);
|
||||
}
|
||||
|
||||
public static decryptBase64Object(input: string): unknown {
|
||||
const data = this.decryptBase64(input);
|
||||
return JSON.parse(data);
|
||||
}
|
||||
|
||||
public static encryptBase64Url(input: string): string {
|
||||
const data = this.decodeUtf8(input);
|
||||
const params = this.encrypt(data);
|
||||
return this.encodeBase64Url(params);
|
||||
}
|
||||
|
||||
public static decryptBase64Url(input: string): string {
|
||||
const data = this.decodeBase64Url(input);
|
||||
const decryptedData = this.decrypt(data);
|
||||
return this.encodeUtf8(decryptedData);
|
||||
}
|
||||
|
||||
public static encryptBase64(input: string): string {
|
||||
const data = this.decodeUtf8(input);
|
||||
const params = this.encrypt(data);
|
||||
return this.encodeBase64(params);
|
||||
}
|
||||
public static decryptBase64(input: string): string {
|
||||
try {
|
||||
const data = this.decodeBase64(input);
|
||||
const decryptedData = this.decrypt(data);
|
||||
return this.encodeUtf8(decryptedData);
|
||||
} catch (error) {
|
||||
console.error("SecurityFunction.decryptBase64 오류:", {
|
||||
input: input?.substring(0, 50) + "...", // 처음 50자만 로그
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public static encrypt(input: WordArray): WordArray {
|
||||
const params = CryptoJS.AES.encrypt(input, KEY, {
|
||||
iv: IV,
|
||||
padding: CryptoJS.pad.Pkcs7,
|
||||
mode: CryptoJS.mode.CBC,
|
||||
});
|
||||
return params.ciphertext;
|
||||
}
|
||||
|
||||
public static decrypt(input: WordArray): WordArray {
|
||||
const params = CryptoJS.lib.CipherParams.create({
|
||||
ciphertext: input,
|
||||
});
|
||||
return CryptoJS.AES.decrypt(params, KEY, {
|
||||
iv: IV,
|
||||
padding: CryptoJS.pad.Pkcs7,
|
||||
mode: CryptoJS.mode.CBC,
|
||||
});
|
||||
}
|
||||
|
||||
public static convertUint8ArrayToWordArray(input: Uint8Array): WordArray {
|
||||
const words: number[] = [];
|
||||
let i = 0;
|
||||
while (i < input.length) {
|
||||
const word =
|
||||
(input[i++] << 24) |
|
||||
(input[i++] << 16) |
|
||||
(input[i++] << 8) |
|
||||
input[i++];
|
||||
words.push(word);
|
||||
}
|
||||
return CryptoJS.lib.WordArray.create(words, words.length * 4);
|
||||
}
|
||||
|
||||
public static convertWordArrayToUint8Array(input: WordArray): Uint8Array {
|
||||
const array = new Uint8Array(input.words.length << 2);
|
||||
for (let i = 0, j = 0; i < input.words.length; i++) {
|
||||
const word = input.words[i];
|
||||
array[j++] = word >> 24;
|
||||
array[j++] = (word >> 16) & 0xff;
|
||||
array[j++] = (word >> 8) & 0xff;
|
||||
array[j++] = word & 0xff;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
public static computeHmacSha256Hex(input: WordArray, key: WordArray): string {
|
||||
return this.encodeHex(this.computeHmacSha256(input, key));
|
||||
}
|
||||
|
||||
public static computeHmacSha256(input: WordArray, key: WordArray): WordArray {
|
||||
return CryptoJS.HmacSHA256(input, key);
|
||||
}
|
||||
|
||||
public static computeSha256Hex(input: WordArray): string {
|
||||
return this.encodeHex(this.computeSha256(input));
|
||||
}
|
||||
|
||||
public static computeSha256(input: WordArray): WordArray {
|
||||
return CryptoJS.SHA256(input);
|
||||
}
|
||||
|
||||
private static convertToSpecialChars(base64: string): string {
|
||||
return Array.from(base64)
|
||||
.map((char) => char.charCodeAt(0).toString(2).padStart(16, "0"))
|
||||
.map((binary) => binary.replace(/0/g, "\u200b").replace(/1/g, "\u200c"))
|
||||
.join("ㅤ");
|
||||
}
|
||||
|
||||
private static convertFromSpecialChars(input: string): string {
|
||||
return input
|
||||
.split("ㅤ")
|
||||
.map((bin) => bin.replace(/\u200b/g, "0").replace(/\u200c/g, "1"))
|
||||
.map((binary) => String.fromCharCode(parseInt(binary, 2)))
|
||||
.join("");
|
||||
}
|
||||
|
||||
public static encodeBase64UrlUtf8(input: string): string {
|
||||
return this.encodeBase64Url(this.decodeUtf8(input));
|
||||
}
|
||||
|
||||
public static decodeBase64UrlUtf8(input: string): string {
|
||||
return this.encodeUtf8(this.decodeBase64Url(input));
|
||||
}
|
||||
|
||||
public static encodeBase64Url(input: WordArray): string {
|
||||
return CryptoJS.enc.Base64url.stringify(input);
|
||||
}
|
||||
|
||||
public static decodeBase64Url(input: string): WordArray {
|
||||
if (this.hasSpecialChars(input)) {
|
||||
const base64url = this.convertFromSpecialChars(input);
|
||||
return CryptoJS.enc.Base64url.parse(base64url);
|
||||
}
|
||||
|
||||
return CryptoJS.enc.Base64url.parse(input);
|
||||
}
|
||||
|
||||
public static encodeBase64Utf8(input: string): string {
|
||||
return this.encodeBase64(this.decodeUtf8(input));
|
||||
}
|
||||
|
||||
public static decodeBase64Utf8(input: string): string {
|
||||
return this.encodeUtf8(this.decodeBase64(input));
|
||||
}
|
||||
|
||||
public static encodeBase64(input: WordArray): string {
|
||||
return CryptoJS.enc.Base64.stringify(input);
|
||||
}
|
||||
|
||||
public static decodeBase64(input: string): WordArray {
|
||||
if (this.hasSpecialChars(input)) {
|
||||
const base64 = this.convertFromSpecialChars(input);
|
||||
return CryptoJS.enc.Base64.parse(base64);
|
||||
}
|
||||
|
||||
return CryptoJS.enc.Base64.parse(input);
|
||||
}
|
||||
|
||||
private static hasSpecialChars(input: string): boolean {
|
||||
return input.includes("\u200b") || input.includes("\u200c");
|
||||
}
|
||||
|
||||
public static encodeHex(input: WordArray): string {
|
||||
return CryptoJS.enc.Hex.stringify(input);
|
||||
}
|
||||
|
||||
public static decodeHex(input: string): WordArray {
|
||||
return CryptoJS.enc.Hex.parse(input);
|
||||
}
|
||||
|
||||
public static encodeUtf8(input: WordArray): string {
|
||||
return CryptoJS.enc.Utf8.stringify(input);
|
||||
}
|
||||
|
||||
public static decodeUtf8(input: string): WordArray {
|
||||
return CryptoJS.enc.Utf8.parse(input);
|
||||
}
|
||||
}
|
||||
20
src/lib/server-api.ts
Normal file
20
src/lib/server-api.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { createHttpClient } from "@/lib/http-client";
|
||||
import { serverEnv } from "@/lib/env.server";
|
||||
|
||||
const createServerApi = async (rootUrl: string, defaultHeaders?: Record<string, string>) => {
|
||||
const cookieStore = await cookies();
|
||||
const accessToken = cookieStore.get("access_token")?.value ?? null;
|
||||
|
||||
return createHttpClient(rootUrl, {
|
||||
getToken: () => accessToken, // 이미 위에서 읽은 값만 참조
|
||||
defaultHeaders: {
|
||||
"content-type": "application/json",
|
||||
...(defaultHeaders ?? {}),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const createBackApi = () => {
|
||||
return createServerApi(serverEnv.API_BACK_SERVER);
|
||||
}
|
||||
62
src/lib/utils.ts
Normal file
62
src/lib/utils.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import {VIEW_DECIMAL_POINT} from "@/const/common.const";
|
||||
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export const formatKoreanBaseDate = (date = new Date()) => {
|
||||
const year = String(date.getFullYear()).slice(-2);
|
||||
return `${year}년 ${date.getMonth() + 1}월 ${date.getDate()}일 기준`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 다양한 형식의 값을 숫자로 파싱합니다.
|
||||
* - 쉼표, 퍼센트, 유니코드 마이너스 자동 처리
|
||||
* - null/undefined/빈문자열/"−" 등은 null 반환
|
||||
* - 유한하지 않은 숫자는 null 반환
|
||||
*/
|
||||
export function parseNumber(
|
||||
value: unknown,
|
||||
options?: {
|
||||
allowComma?: boolean; // 기본값: true
|
||||
allowPercent?: boolean; // 기본값: true
|
||||
allowMinus?: boolean; // 기본값: true (유니코드 마이너스 포함)
|
||||
}
|
||||
): number | null {
|
||||
const { allowComma = true, allowPercent = true, allowMinus = true } = options ?? {};
|
||||
|
||||
if (value === null || value === undefined) return null;
|
||||
|
||||
if (typeof value === "number") {
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
if (typeof value === "string") {
|
||||
let s = value.trim();
|
||||
|
||||
if (s === "" || s === "-" || s === "−") return null;
|
||||
|
||||
s = s.replaceAll("(", "");
|
||||
s = s.replaceAll(")", "");
|
||||
|
||||
if (allowComma) s = s.replaceAll(",", "");
|
||||
if (allowPercent) s = s.replaceAll("%", "");
|
||||
if (allowMinus) s = s.replaceAll("−", "-"); // 유니코드 마이너스 -> ASCII 마이너스
|
||||
|
||||
const n = Number(s);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export const roundNumber = (num: number|null, decimalPoint?: number) => {
|
||||
if(num == null) return null;
|
||||
|
||||
decimalPoint ??= VIEW_DECIMAL_POINT;
|
||||
const factor = 10 ** decimalPoint;
|
||||
return Math.round(num * factor) / factor;
|
||||
};
|
||||
Reference in New Issue
Block a user