forked from flaredragon/hackvsit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.js
56 lines (47 loc) · 1.42 KB
/
store.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
var fs = require('fs');
var db = 'scraps.json';
var userTokens = {};
exports.getUserToken = function (userId) {
return userTokens[userId];
}
exports.saveUserToken = function (userId, token) {
userTokens[userId] = token;
}
var chats = {};
var conversationId = function (userId, chat) {
if (chat.startsWith('u:') || chat.startsWith('b:')) {
return [userId, chat].sort().join('|');
} else {
return chat;
}
}
exports.saveScrap = function (userId, chat, text) {
var cid = conversationId(userId, chat);
if (!chats[cid]) {
chats[cid] = [text];
} else {
chats[cid].push(text);
}
};
exports.listScraps = function (userId, chat) {
return chats[conversationId(userId, chat)];
};
var readDatabase = function () {
try {
var stringContent = fs.readFileSync(db);
var content = JSON.parse(stringContent);
userTokens = content.userTokens;
chats = content.chats;
} catch (e) {
console.log('Couldn\'t read db, starting empty.\nError:', e);
}
};
var saveDatabase = function () {
console.log('Saving db');
var stringContent = JSON.stringify({ userTokens: userTokens, chats: chats });
fs.writeFileSync(db, stringContent);
};
readDatabase();
process.on('SIGINT', function () { console.log('SIGINT'); process.exit(); });
process.on('SIGTERM', function () { console.log('SIGTERM'); process.exit(); });
process.on('exit', saveDatabase);