From 8292cfc1c719b370821bba056855f84ecf9842b7 Mon Sep 17 00:00:00 2001 From: Tobi Saputra Date: Mon, 3 Mar 2025 20:53:44 +0700 Subject: [PATCH] feat: added cookie manager for cli --- .gitignore | 3 ++- .npmignore | 3 ++- src/types/cookieManager.ts | 14 ++++++++++++++ src/utils/cookieManager.ts | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/types/cookieManager.ts create mode 100644 src/utils/cookieManager.ts diff --git a/.gitignore b/.gitignore index 1a804b2..7abc476 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,5 @@ yarn.lock lib test.js bun.lockb -tsconfig.tsbuildinfo \ No newline at end of file +tsconfig.tsbuildinfo +cookies.json \ No newline at end of file diff --git a/.npmignore b/.npmignore index 11e7395..5131d20 100644 --- a/.npmignore +++ b/.npmignore @@ -9,4 +9,5 @@ tsconfig.json src test.js bun.lockb -tsconfig.tsbuildinfo \ No newline at end of file +tsconfig.tsbuildinfo +cookies.json \ No newline at end of file diff --git a/src/types/cookieManager.ts b/src/types/cookieManager.ts new file mode 100644 index 0000000..f18a6e0 --- /dev/null +++ b/src/types/cookieManager.ts @@ -0,0 +1,14 @@ +export interface Cookie { + name: string + value: string + domain?: string + path?: string + expires?: Date + secure?: boolean +} + +export interface ICookieManager { + getCookie(): string | null + setCookie(value: string): void + deleteCookie(): void +} diff --git a/src/utils/cookieManager.ts b/src/utils/cookieManager.ts new file mode 100644 index 0000000..eb533d8 --- /dev/null +++ b/src/utils/cookieManager.ts @@ -0,0 +1,33 @@ +import { ICookieManager } from "../types/cookieManager" + +export class CookieManager implements ICookieManager { + private cookieName: string + + constructor(cookieName: string) { + this.cookieName = cookieName + } + + public getCookie(): string | null { + if (typeof window === "undefined") return null + const cookies = document.cookie.split(";") + const cookie = cookies.find((c) => + c.trim().startsWith(`${this.cookieName}=`) + ) + if (!cookie) return null + return decodeURIComponent(cookie.split("=")[1]) + } + + public setCookie(value: string): void { + if (typeof window === "undefined") return + const date = new Date() + date.setTime(date.getTime() + 30 * 24 * 60 * 60 * 1000) // 30 days + document.cookie = `${this.cookieName}=${encodeURIComponent( + value + )}; expires=${date.toUTCString()}; path=/` + } + + public deleteCookie(): void { + if (typeof window === "undefined") return + document.cookie = `${this.cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/` + } +}