Skip to content

Commit

Permalink
add cookie methods
Browse files Browse the repository at this point in the history
  • Loading branch information
alvinsj committed Jun 8, 2024
1 parent bbed641 commit 4f121a4
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
56 changes: 56 additions & 0 deletions src/lib/__tests__/cookie.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { describe, test, expect, beforeEach } from "vitest"
import { saveCookie, getCookie, deleteCookie } from "../cookie"

describe("saveCookie", () => {
test("throws error on empty name", () => {
expect(() => saveCookie())
.toThrowError("Cookie name is required")
})

test("saves empty value", () => {
saveCookie("a", "")
expect(document.cookie).toMatch("a=")
})

test("saves cookie", () => {
saveCookie("a", "1234")
expect(document.cookie).toMatch("a=1234")
})

test("saves cookie with latest value", () => {
saveCookie("a", "1234")
saveCookie("a", "124")
expect(document.cookie).toMatch("a=124")
expect(document.cookie).not.toMatch("a=1234")
})
})

describe("getCookie", () => {
test("gets none", () => {
saveCookie("b", "54321")
expect(getCookie("c")).toBeUndefined()
})

test("gets cookie", () => {
saveCookie("b", "54321")
expect(getCookie("b")).toBe("54321")
})
})

describe("deleteCookie", () => {
test("deletes cookie", () => {
saveCookie("c", "12345")
saveCookie("d", "54321")
deleteCookie("c")
expect(document.cookie).not.toMatch("c=12345")
expect(document.cookie).toMatch("d=54321")
})

test("deletes none", () => {
saveCookie("one", "12345")
saveCookie("two", "54321")
deleteCookie("e")
expect(document.cookie).toMatch("one=12345")
expect(document.cookie).toMatch("two=54321")
})
})
18 changes: 18 additions & 0 deletions src/lib/cookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export const saveCookie = (name: string, value: string, mins: number = 60) => {
if (!name)
throw new Error('Cookie name is required')

const date = new Date()
date.setTime(date.getTime() + mins * 60 * 1000)
document.cookie = `${name}=${value};Expires=${date.toUTCString()}; path=/; Secure; SameSite=None`
}

export const getCookie = (name: string) => {
const value = `; ${document.cookie}`
const parts = value.split(`; ${name}=`)
if (parts.length === 2) return parts.pop()?.split(';').shift()
}

export const deleteCookie = (name: string) => {
document.cookie = `${name}=; Max-Age=0; path=/; Secure; SameSite=None`
}

0 comments on commit 4f121a4

Please sign in to comment.