-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-storage.ts
More file actions
38 lines (28 loc) · 1.08 KB
/
session-storage.ts
File metadata and controls
38 lines (28 loc) · 1.08 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
import type { StorageAdapter } from "grammy";
import type { Database } from "bun:sqlite";
export class SqliteSessionStorage<T> implements StorageAdapter<T> {
private db: Database;
constructor(db: Database) {
this.db = db;
}
read(key: string): T | undefined {
const query = this.db.query<{ data: string }, [string]>("SELECT data FROM sessions WHERE user_id = ?");
const result = query.get(key);
if (!result) {
return undefined;
}
return JSON.parse(result.data) as T;
}
write(key: string, value: T): void {
const now = Date.now();
const data = JSON.stringify(value);
const upsertQuery = this.db.query(
"INSERT INTO sessions (user_id, data, updated_at) VALUES (?, ?, ?) ON CONFLICT(user_id) DO UPDATE SET data = excluded.data, updated_at = excluded.updated_at",
);
upsertQuery.run(key, data, now);
}
delete(key: string): void {
const deleteQuery = this.db.query("DELETE FROM sessions WHERE user_id = ?");
deleteQuery.run(key);
}
}