-
Notifications
You must be signed in to change notification settings - Fork 26k
/
cookies.ts
72 lines (60 loc) · 1.8 KB
/
cookies.ts
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
import cookie from 'next/dist/compiled/cookie'
import { CookieSerializeOptions } from '../types'
const normalizeCookieOptions = (options: CookieSerializeOptions) => {
options = Object.assign({}, options)
if (options.maxAge) {
options.expires = new Date(Date.now() + options.maxAge)
options.maxAge /= 1000
}
if (options.path == null) {
options.path = '/'
}
return options
}
const serializeValue = (value: unknown) =>
typeof value === 'object' ? `j:${JSON.stringify(value)}` : String(value)
export class Cookies extends Map {
constructor(input: string | null | undefined) {
const parsedInput = typeof input === 'string' ? cookie.parse(input) : {}
super(Object.entries(parsedInput))
}
set(key: string, value: unknown, options: CookieSerializeOptions = {}) {
return super.set(
key,
cookie.serialize(
key,
serializeValue(value),
normalizeCookieOptions(options)
)
)
}
}
export class NextCookies extends Cookies {
response: Request | Response
constructor(response: Request | Response) {
super(response.headers.get('cookie'))
this.response = response
}
set(...args: [key: string, value: unknown, options: CookieSerializeOptions]) {
const store = super.set(...args)
this.response.headers.append('set-cookie', store.get(args[0]))
return store
}
delete(key: any) {
const isDeleted = super.delete(key)
if (isDeleted) {
const setCookie = this.response.headers
.get('set-cookie')
?.split(', ')
.filter((value) => !value.startsWith(`${key}=`))
.join(',')
if (setCookie) {
this.response.headers.set('set-cookie', setCookie)
} else {
this.response.headers.delete('set-cookie')
}
}
return isDeleted
}
}
export { CookieSerializeOptions }