/
SqliteStore.ts
48 lines (37 loc) · 1.41 KB
/
SqliteStore.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
import { DB } from "https://deno.land/x/sqlite@v3.4.0/mod.ts"
import Store from './Store.ts'
import { SessionData } from '../Session.ts'
export default class SqliteStore implements Store {
db: DB
tableName: string
constructor(db : DB, tableName = 'sessions') {
this.db = db
this.tableName = tableName
this.db.query(`CREATE TABLE IF NOT EXISTS ${this.tableName} (id TEXT, data TEXT)`)
}
sessionExists(sessionId : string) {
let session = ''
for (const [sess] of this.db.query<string[]>(`SELECT data FROM ${this.tableName} WHERE id = ?`, [sessionId])) {
session = sess
}
return session ? true : false;
}
getSessionById(sessionId : string) {
let session = ''
for (const [sess] of this.db.query<string[]>(`SELECT data FROM ${this.tableName} WHERE id = ?`, [sessionId])) {
session = sess
}
return session ? JSON.parse(session) as SessionData : null;
}
createSession(sessionId : string, initialData : SessionData) {
this.db.query(`INSERT INTO ${this.tableName} (id, data) VALUES (?, ?)`, [sessionId, JSON.stringify(initialData)]);
}
deleteSession(sessionId : string) {
this.db.query(`DELETE FROM ${this.tableName} WHERE id = ?`, [sessionId])
}
persistSessionData(sessionId : string, sessionData : SessionData) {
this.db.query(`UPDATE ${this.tableName} SET data = ? WHERE id = ?`, [
JSON.stringify(sessionData), sessionId
]);
}
}