-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabaseHandler.js
261 lines (201 loc) · 6.53 KB
/
DatabaseHandler.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
var fs = require("fs");
var Promise = require("es6-promise").Promise;
var sqlite3 = require("sqlite3").verbose();
// Can be run in memory!
//var db = new sqlite3.Database(':memory:');
//to run in memory, provide ":memory:" as databaseFile
var DatabaseHandler = function(databaseFile){
var file = databaseFile;
var db = new sqlite3.Database(file);
var _constructor = function(){
_initializeDBIfEmpty();
};
var _initializeDBIfEmpty = function(){
_createFile();
_createTables();
};
var _createFile = function(){
var exists = fs.existsSync(file);
if(!exists) {
console.log("Creating DB file:"+file);
fs.openSync(file, "w");
}
};
var _createTables = function(){
db.serialize(function() {
db.run("CREATE TABLE if not exists applicationLog('id' INTEGER primary key AUTOINCREMENT,'userId' varchar(40), 'type' varchar(20), 'message' varchar(2500), 'timestamp' DATETIME DEFAULT CURRENT_TIMESTAMP)");
db.run("CREATE TABLE if not exists user('id' INTEGER primary key AUTOINCREMENT,'userId' varchar(40), 'name' varchar(40),'participating' varchar(6), 'ovinger' int,'requests' int, 'creation' DATETIME DEFAULT CURRENT_TIMESTAMP)");
});
};
var insertClient = function(userId){
return new Promise(function(resolve, reject){
var values = {
$userId:userId,
};
//We dont use prepared statements as it will be a long delay between insertions
var stmt = db.run("INSERT INTO user (userId,ovinger,requests) VALUES ($userId,0,0)",values,function(error){
if(error !==null){
reject(error);
return;
}
resolve();
});
})
};
var setClientName = function(clientId,name){
return new Promise(function(resolve, reject){
var values = {
$clientId:clientId,
$name:name
};
console.log("Setting client name for user:",clientId);
//Check if client exists
_createClientIfNotExists(clientId).then(function(){
var stmt = db.run("UPDATE user SET name = $name WHERE userId= $clientId;",values,function(error){
if(error == null){
resolve()
}else{
reject(error);
}
});
},function(error){
reject(error);
});
})
};
var _createClientIfNotExists = function(clientId){
return new Promise(function(resolve, reject){
var values = {
$clientId: clientId
}
var existsStms = db.run("SELECT * FROM user WHERE userId= $clientId;",values,function(error,rows){
if(error !== null){
reject(error);
}
if(rows === undefined || rows.length < 1){
insertClient(clientId).then(function(){
resolve();
},function(error){reject(error)});
}else{
resolve();
}
})
})
}
var setClientParticipating= function(clientId,participating){
return new Promise(function(resolve, reject){
var values = {
$clientId:clientId,
$participating:participating
};
var stmt = db.run("UPDATE user SET participating = $participating WHERE userId= $clientId;",values,function(error){
if(error == null){
resolve()
}else{
reject(error);
}
});
})
};
var getIdFromClientName = function(name){
return new Promise(function(resolve,reject){
console.log("Cheking db for"+name);
db.get("SELECT userId,name FROM user WHERE name = $name",{$name:name},function(error,rows){
console.log("Got result",error,rows," for username:",name);
if(rows === undefined || rows.name === undefined || rows.name.length === 0){
console.log("Rejecting promise")
reject(error);
}else{
resolve(rows.userId);
}
});
});
};
var insertApplicationLog = function(userId,type,message){
var values = {
$userId:userId,
$type:type,
$message: message
};
//We dont use prepared statements as it will be a long delay between insertions
var stmt = db.run("INSERT INTO applicationLog (userId,type,message) VALUES ($userId,$type,$message)",values);
};
// Options: {userId:,type:,after:,before:}
var fetchApplicationLog = function(options){
return new Promise(function(resolve,reject){
var wherePart = _generateSQLWherePartFromOptions(options);
_fetchApplicationLogGivenWhere(wherePart,options).then(
function(result){
resolve(result);
}).catch(function(error){
reject(error);
});
});
};
var _fetchApplicationLogGivenWhere = function(whereClause,options){
return new Promise(function(resolve,reject){
console.log("SELECT * FROM applicationLog "+whereClause);
db.all("SELECT * FROM applicationLog "+whereClause+";",{},function(error,rows){
console.log("got",rows+error)
if(error!==null){reject(error);}
resolve(rows);
});
});
};
var _generateSQLWherePartFromOptions = function(options){
var conditions = _generateArrayOfConditions(options);
if(conditions.length === 0){return "";}
var whereString = _generateStringOfConditions(conditions);
console.log(whereString);
return whereString;
};
var _generateArrayOfConditions = function(options){
var conditions = [];
for(var field in options){
if(!options.hasOwnProperty(field)){continue;}
var condition = _optionToCondition(field,options[field]);
conditions.push(condition);
}
return conditions;
};
var _optionToCondition = function(option,value){
if(option == 'before'){
return "timestamp < "+value;
}
if(option == 'after'){
return "timestamp > "+value;
}
return option+ " = '"+value+"'";
};
var _generateStringOfConditions = function(conditionsArray){
var conditionString = " WHERE ";
for(var i=0;i<conditionsArray.length-1;i++){
conditionString+=conditionsArray[i] + " AND ";
}
conditionString+=conditionsArray[i] ;
return conditionString;
};
var _closeConnection = function(){
db.close();
};
_constructor();
var publicApi = {
insertClient:insertClient,
insertApplicationLog:insertApplicationLog,
setClientName:setClientName,
setClientParticipating:setClientParticipating,
getIdFromClientName:getIdFromClientName,
fetchApplicationLog:fetchApplicationLog
};
//TestCode
publicApi.__forTesting = {_optionToCondition:_optionToCondition,_generateSQLWherePartFromOptions:_generateSQLWherePartFromOptions};
return publicApi;
};
/*
var databaseHandler = new DatabaseHandler();
databaseHandler.insertApplicationLog(12345,"Test","Dette er en lang melding");
databaseHandler.insertApplicationLog(54321,"Test","Dette er en lang melding");
databaseHandler.fetchApplicationLog().then(function(result){ console.log("1",result);}).catch(function(error){console.log(error);});
databaseHandler.fetchApplicationLog({userId:12345}).then(function(result){ console.log(2,result);}).catch(function(error){console.log(error);});
*/
module.exports = DatabaseHandler;