feat: added cookie manager for cli

This commit is contained in:
Tobi Saputra 2025-03-03 20:53:44 +07:00
parent b8afc30292
commit 8292cfc1c7
4 changed files with 51 additions and 2 deletions

3
.gitignore vendored
View File

@ -5,4 +5,5 @@ yarn.lock
lib lib
test.js test.js
bun.lockb bun.lockb
tsconfig.tsbuildinfo tsconfig.tsbuildinfo
cookies.json

View File

@ -9,4 +9,5 @@ tsconfig.json
src src
test.js test.js
bun.lockb bun.lockb
tsconfig.tsbuildinfo tsconfig.tsbuildinfo
cookies.json

View File

@ -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
}

View File

@ -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=/`
}
}