forked from alephjs/aleph.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.ts
89 lines (75 loc) · 2.44 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { setCookieHeader } from "./helpers.ts";
import type { Session, SessionOptions, SessionStorage } from "./types.ts";
export class MemorySessionStorage implements SessionStorage {
#store: Map<string, [unknown, number]> = new Map();
get(sid: string): Promise<unknown | undefined> {
const [data, expires] = this.#store.get(sid) ?? [undefined, 0];
if (expires > 0 && Date.now() > expires) {
this.#store.delete(sid);
return Promise.resolve(undefined);
}
return Promise.resolve(data);
}
set(sid: string, data: unknown, expires: number): Promise<void> {
this.#store.set(sid, [data, expires]);
return Promise.resolve();
}
delete(sid: string): Promise<void> {
this.#store.delete(sid);
return Promise.resolve();
}
}
const defaultSessionStorage = new MemorySessionStorage();
export class SessionImpl<StoreType extends Record<string, unknown>> implements Session<StoreType> {
#id: string;
#options: SessionOptions;
#store: StoreType | undefined;
#storage: SessionStorage;
constructor(id: string, options: SessionOptions = {}) {
this.#id = id;
this.#options = options;
this.#storage = options.storage ?? defaultSessionStorage;
}
get id(): string {
return this.#id;
}
get store(): StoreType | undefined {
return this.#store;
}
async read(): Promise<void> {
this.#store = (await this.#storage.get(this.#id)) as StoreType | undefined;
}
async update(store: StoreType | ((prev: StoreType | undefined) => StoreType)): Promise<string> {
if (typeof store !== "object" && typeof store !== "function") {
throw new Error("store must be a valid object or a function");
}
let nextStore: StoreType | undefined;
if (typeof store === "function") {
nextStore = store(this.#store);
} else {
nextStore = store;
}
await this.#storage.set(this.#id, nextStore, Date.now() + 1000 * (this.#options.maxAge ?? 1800));
this.#store = nextStore;
return setCookieHeader(
this.#options.cookie?.name ?? "session",
this.#id,
{
...this.#options.cookie,
expires: new Date(Date.now() + 1000 * (this.#options.maxAge ?? 1800)),
},
);
}
async end(): Promise<string> {
await this.#storage.delete(this.#id);
this.#store = undefined;
return setCookieHeader(
this.#options.cookie?.name ?? "session",
"",
{
...this.#options.cookie,
expires: new Date(0),
},
);
}
}