-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.ts
70 lines (60 loc) · 1.56 KB
/
session.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
import type { Ad, User } from '@prisma/client'
interface Session {
id?: string
user: User
ad?: AdState
}
interface AdState {
timeRemaining: number
lastUpdated: number
adWatched: Ad
nextPage: string
skippable: boolean
}
const sessionStore = new Map<string, Session>()
export class SessionRequest extends Request {
session?: Session
sessionValid = true
parsedUrl: URL
ip!: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
jsonBody: any
constructor(
request: Request,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public data: FormData | any | undefined,
public params: Record<string, string>
) {
super(request)
const s = this.headers.get('Cookie')?.split('session=')
const sessId = s && s.length > 1 ? s[1] : undefined
if (sessId) {
this.session = sessionStore.get(sessId)
}
if (!this.session) {
this.sessionValid = false
}
this.parsedUrl = new URL(request.url)
}
clearSession() {
if (this.session && this.session.id) {
sessionStore.delete(this.session.id)
}
this.session = undefined
}
}
export function setSession(res: Response, session: Session | undefined): Response {
if (session == undefined) {
res.headers.append(
'Set-Cookie',
`session=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT`
)
return res
}
if (!session.id) {
session.id = Math.random().toString(36).slice(2)
}
sessionStore.set(session.id, session)
res.headers.append('Set-Cookie', `session=${session.id}; Path=/`)
return res
}