-
Notifications
You must be signed in to change notification settings - Fork 1
/
userdb_helper.js
114 lines (103 loc) · 2.64 KB
/
userdb_helper.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
"use strict";
/* http://www.sqlitetutorial.net/sqlite-nodejs/ */
var _ = require("lodash");
var sqlite3 = require("sqlite3").verbose();
const db_file = ".data/users.db";
function User_DB_Helper() {}
User_DB_Helper.prototype.initDB = function() {
let db = new sqlite3.Database(db_file, err => {
if (err) {
return console.error(err.message);
}
let query = `CREATE TABLE IF NOT EXISTS
users(id text PRIMARY KEY,
state text NOT NULL)`;
db.run(query, function(err) {
if (err) {
return console.log(err.message);
}
});
});
db.close(err => {
if (err) {
return console.error(err.message);
}
});
};
User_DB_Helper.prototype.getState = function(userID) {
return new Promise(function(resolve, reject) {
let db = new sqlite3.Database(db_file, err => {
if (err) {
reject(err);
return console.error(err.message);
}
let query = `SELECT state FROM users WHERE id = ?`;
db.get(query, userID, (err, row) => {
if (err) {
reject(err);
console.log(err.message);
} else if (_.isUndefined(row)) {
//This means there's no user with userId
resolve();
} else {
resolve(row.state);
}
});
});
db.close(err => {
if (err) {
return console.error(err.message);
}
});
});
};
User_DB_Helper.prototype.setState = function(userID, state) {
return new Promise(function(resolve, reject) {
let db = new sqlite3.Database(db_file, err => {
if (err) {
reject(err);
return console.error(err.message);
}
let query = `INSERT OR REPLACE INTO users (id, state)
VALUES ('${userID}', '${state}')`;
db.run(query, err => {
if (err) {
reject(err);
console.log(err.message);
} else {
resolve(true);
}
});
});
db.close(err => {
if (err) {
return console.error(err.message);
}
});
});
};
User_DB_Helper.prototype.deleteUser = function(userID) {
return new Promise(function(resolve, reject) {
let db = new sqlite3.Database(db_file, err => {
if (err) {
reject(err);
return console.error(err.message);
}
let query = `DELETE FROM users WHERE id = ?`;
db.run(query, userID, err => {
if (err) {
reject(err);
console.log(err.message);
} else {
resolve(true);
}
});
});
db.close(err => {
if (err) {
return console.error(err.message);
}
});
});
};
module.exports = User_DB_Helper;