-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathcookieAccess.ts
More file actions
73 lines (62 loc) · 2.11 KB
/
cookieAccess.ts
File metadata and controls
73 lines (62 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { dateNow } from '../tools/utils/timeUtils'
import type { CookieOptions } from './cookie'
import { getCookies, setCookie, deleteCookie } from './cookie'
import type { CookieStore } from './browser.types'
export interface CookieAccessor {
getAll(name: string): Promise<string[]>
set(name: string, value: string, expireDelay: number, options?: CookieOptions): Promise<void>
delete(name: string, options?: CookieOptions): Promise<void>
}
interface CookieStoreWindow {
cookieStore?: CookieStore
}
export function createCookieAccessor(cookieOptions: CookieOptions): CookieAccessor {
const store = (globalThis as CookieStoreWindow).cookieStore
if (store) {
return createCookieStoreAccessor(store, cookieOptions)
}
return createDocumentCookieAccessor()
}
function createCookieStoreAccessor(store: CookieStore, cookieOptions: CookieOptions): CookieAccessor {
return {
async getAll(name: string): Promise<string[]> {
const cookies = await store.getAll(name)
return cookies.map((cookie) => cookie.value)
},
async set(name: string, value: string, expireDelay: number): Promise<void> {
const expires = new Date(dateNow() + expireDelay)
await store.set({
name,
value,
domain: cookieOptions.domain,
path: '/',
expires,
sameSite: cookieOptions.crossSite ? 'none' : 'strict',
secure: cookieOptions.secure,
partitioned: cookieOptions.partitioned,
})
},
async delete(name: string): Promise<void> {
await store.delete({
name,
domain: cookieOptions.domain,
path: '/',
})
},
}
}
function createDocumentCookieAccessor(): CookieAccessor {
return {
getAll(name: string): Promise<string[]> {
return Promise.resolve(getCookies(name))
},
set(name: string, value: string, expireDelay: number, options?: CookieOptions): Promise<void> {
setCookie(name, value, expireDelay, options)
return Promise.resolve()
},
delete(name: string, options?: CookieOptions): Promise<void> {
deleteCookie(name, options)
return Promise.resolve()
},
}
}