-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
97 lines (87 loc) · 2.87 KB
/
database.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
const fs = require("fs");
const hash = require("object-hash");
const fileName = "data.json";
const msPerDay = 1000 * 60 * 60 * 24;
const dayForSession = 2;
class database {
constructor() {
this.loadData();
}
getTable(name) {
if (name == undefined) {
return undefined;
}
return this.data[name];
}
async saveData(name, data) {
this.data[name] = data;
var dataString = JSON.stringify(this.data);
fs.writeFile(fileName, dataString, "utf8", function (err) {
if (err) {
console.log("error on save ", err);
}
});
}
loadData() {
try {
let data = fs.readFileSync(fileName);
this.data = JSON.parse(data);
} catch (error) {
console.log("error on load ", error);
}
}
getIdUser(idSession) {
if (idSession == undefined) {
return undefined;
}
let ret = this.data.Session.filter((s) => s.idSession == idSession)[0];
if (ret == undefined) {
return undefined;
} else if (Math.floor(new Date() - new Date(ret.lastLogin)) / msPerDay > dayForSession) {
this.data.Session = this.data.Session.filter((s) => s.idSession != idSession);
this.saveData("Session", this.data.Session);
return undefined;
} else {
return ret.idUser;
}
}
async login(idUser) {
let ret = this.data.Session.filter((s) => s.idUser == idUser)[0];
if (ret != undefined) {
if (Math.floor(new Date() - new Date(ret.lastLogin)) / msPerDay > dayForSession) {
this.data.Session = this.data.Session.filter((s) => s.idUser != idUser);
} else {
return ret.idSession;
}
}
let d = new Date();
let obj = { idUser: idUser, lastLogin: d };
let idSession = hash(obj);
obj.idSession = idSession;
this.data.Session.push(obj);
await this.saveData("Session", this.data.Session);
return idSession;
}
logout(idSession) {
this.data.Session = this.data.Session.filter((s) => s.idSession != idSession);
this.saveData("Session", this.data.Session);
}
searchKey(tableName, fieldKeyName, keyToSearch) {
let table = this.getTable(tableName);
let ret = [];
if (table != undefined) {
for (let i = 0; i < table.length; i++) {
if (table[i][fieldKeyName] == keyToSearch) {
ret.push(i);
}
}
}
if (ret.length > 1) {
return ret;
} else if (ret.length == 1) {
return ret[0];
}
return undefined;
}
}
module.exports = database;