-
Notifications
You must be signed in to change notification settings - Fork 1
/
subscriptions-db.js
66 lines (59 loc) · 2.09 KB
/
subscriptions-db.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
/**
* @typedef {Object} Subscription
* @property {string} username
* @property {string} expirationDate - Expiry date, ISO8601 formatted
* @property {Object} purchase - Information about the user's purchases status, as provided by iaptic
*/
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database('subscriptions.db');
db.run('CREATE TABLE IF NOT EXISTS subscriptions (username TEXT PRIMARY KEY, expirationDate TEXT, purchase TEXT)');
/**
* Update the user's subscription
*
* @param subscription {Subscription}
*/
function update(username, purchase) {
const expirationDate = purchase ? purchase.expirationDate : null;
const purchaseJSON = purchase ? JSON.stringify(purchase) : null;
db.run('INSERT INTO subscriptions VALUES (?, ?, ?) ON CONFLICT(username) DO UPDATE SET expirationDate = ?, purchase = ?',
username,
expirationDate,
purchaseJSON,
expirationDate,
purchaseJSON,
);
}
/** Fetch the user's subscription, if any */
function fetch(username, callback) {
db.each('SELECT * FROM subscriptions WHERE username = ?', username, (err, row) => {
if (!callback) return;
if (err) {
callback(err);
callback = null;
}
else {
callback(null, {
username: row.username,
expirationDate: row.expirationDate,
purchase: row.purchase ? JSON.parse(row.purchase) : null,
});
callback = null;
}
}, () => {
if (!callback) return;
callback(null, {username, purchase: null, expirationDate: null});
});
}
function remove(username, callback) {
db.run('DELETE FROM subscriptions WHERE username = ?', [username], function(err) {
if (err) {
console.error('Error attempting to delete subscription:', err);
callback(err);
return;
}
const wasDeleted = this.changes > 0;
console.log(`Subscription for user ${username} ${wasDeleted ? 'deleted successfully' : 'not found or already deleted'}.`);
callback(null, wasDeleted);
});
}
module.exports = {update, fetch, remove}