251121_01_ENH : 로그인 및 인증 저장, api통신 시 자동으로 accessKey 붙게 조치
This commit is contained in:
105
src/store/cookie/cookie.ts
Normal file
105
src/store/cookie/cookie.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
"use client";
|
||||
|
||||
import type { CookieKey } from "./cookie-keys";
|
||||
|
||||
export type CookieSetOptions = {
|
||||
days?: number; // 만료일: 기본 365일
|
||||
path?: string; // 기본 "/"
|
||||
secure?: boolean;
|
||||
sameSite?: "Lax" | "Strict" | "None";
|
||||
};
|
||||
|
||||
function isBrowser() {
|
||||
return typeof document !== "undefined";
|
||||
}
|
||||
|
||||
function buildCookieString(
|
||||
key: CookieKey,
|
||||
value: string,
|
||||
options: CookieSetOptions = {},
|
||||
): string {
|
||||
const {
|
||||
days = 365,
|
||||
path = "/",
|
||||
secure = false,
|
||||
sameSite = "Lax",
|
||||
} = options;
|
||||
|
||||
let cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
||||
|
||||
// 만료일
|
||||
if (Number.isFinite(days)) {
|
||||
const expires = new Date();
|
||||
expires.setDate(expires.getDate() + days);
|
||||
cookie += `; Expires=${expires.toUTCString()}`;
|
||||
}
|
||||
|
||||
if (path) {
|
||||
cookie += `; Path=${path}`;
|
||||
}
|
||||
|
||||
if (secure) {
|
||||
cookie += "; Secure";
|
||||
}
|
||||
|
||||
if (sameSite) {
|
||||
cookie += `; SameSite=${sameSite}`;
|
||||
}
|
||||
|
||||
return cookie;
|
||||
}
|
||||
|
||||
export const cookieStore = {
|
||||
/**
|
||||
* 문자열 값 가져오기 (없으면 null)
|
||||
*/
|
||||
get(key: CookieKey): string | null {
|
||||
if (!isBrowser()) return null;
|
||||
|
||||
try {
|
||||
const name = encodeURIComponent(key) + "=";
|
||||
const cookies = document.cookie ? document.cookie.split("; ") : [];
|
||||
|
||||
for (const c of cookies) {
|
||||
if (c.startsWith(name)) {
|
||||
const value = c.substring(name.length);
|
||||
return decodeURIComponent(value);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 문자열 값 저장
|
||||
*/
|
||||
set(key: CookieKey, value: string, options?: CookieSetOptions) {
|
||||
if (!isBrowser()) return;
|
||||
|
||||
try {
|
||||
const cookie = buildCookieString(key, value, options);
|
||||
document.cookie = cookie;
|
||||
} catch {
|
||||
// 쿠키 설정 실패는 조용히 무시
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 쿠키 삭제
|
||||
*/
|
||||
remove(key: CookieKey, options?: Omit<CookieSetOptions, "days">) {
|
||||
if (!isBrowser()) return;
|
||||
|
||||
try {
|
||||
document.cookie = buildCookieString(key, "", {
|
||||
...(options ?? {}),
|
||||
days: -1, // 과거로 설정해서 삭제
|
||||
});
|
||||
} catch {
|
||||
// 무시
|
||||
}
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user