-
Notifications
You must be signed in to change notification settings - Fork 3
/
dao.js
70 lines (63 loc) · 1.59 KB
/
dao.js
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 sqlite from 'sqlite3';
import { config } from 'dotenv';
const { Database } = sqlite;
config();
class AppDAO {
constructor() {
this.db = new Database(process.env.dbPath, (err) => {
if (err) {
console.log('Could not connect to database:', err)
} else {
this.ensureTable();
}
})
}
run(sql, params = []) {
return new Promise((resolve, reject) => {
this.db.run(sql, params, function (err) {
if (err) {
console.log('Error running sql: ' + sql)
console.log(err)
reject(err)
} else {
resolve(this.changes)
}
})
})
}
insertSubscription(sub) {
const sql = `INSERT OR IGNORE INTO subscriptions (endpoint, p256dh, auth) VALUES (
'${sub.endpoint}',
'${sub.p256dh}',
'${sub.auth}'
)`
return this.run(sql);
}
deleteSubscription(sub) {
const sql = `DELETE FROM subscriptions WHERE p256dh = '${sub.keys.p256dh}' AND auth = '${sub.keys.auth}'`
return this.run(sql);
}
getAllSubscriptions() {
const sql = 'SELECT * FROM subscriptions';
return new Promise((resolve, reject) => {
this.db.all(sql, (err, rows) => {
if (err) {
console.log('Error running sql: ' + sql)
console.log(err)
reject(err)
} else {
resolve(rows)
}
})
})
}
ensureTable() {
const sql = `CREATE TABLE IF NOT EXISTS subscriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
endpoint TEXT,
p256dh TEXT UNIQUE,
auth TEXT)`
return this.run(sql)
}
}
export default AppDAO