forked from sunnypatel165/flockSO
-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.js
executable file
·76 lines (61 loc) · 1.61 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict';
var fs = require('fs');
var dbFile = 'db.json';
// Everything is stored here
var db = {
users: {},
alarms: []
};
// Read db file on startup and save on exit
var readDatabase = function () {
try {
var stringContent = fs.readFileSync(dbFile);
db = JSON.parse(stringContent);
} catch (e) {
console.log('No db found, creating %s', dbFile);
}
};
var saveDatabase = function () {
console.log('Saving db');
var stringContent = JSON.stringify(db);
fs.writeFileSync(dbFile, stringContent);
};
readDatabase();
process.on('SIGINT', function () { console.log('SIGINT'); process.exit(); });
process.on('SIGTERM', function () { console.log('SIGTERM'); process.exit(); });
process.on('exit', saveDatabase);
// Accessors
exports.getToken = function (userId) {
return db.users[userId];
};
exports.saveToken = function (userId, token) {
db.users[userId] = token;
};
exports.peekAlarm = function () {
if (db.alarms.length > 0) {
return db.alarms[0];
} else {
return null;
}
};
exports.removeAlarm = function (alarm) {
var index = db.alarms.indexOf(alarm);
if (index !== -1) {
db.alarms.splice(index, 1);
}
};
exports.addAlarm = function (alarm) {
var alarms = db.alarms;
var insertAt = Math.max(0, alarms.findIndex(function (x) {
return alarm.time < x.time;
}));
alarms.splice(insertAt, 0, alarm);
};
exports.userAlarms = function (userId) {
return db.alarms.filter(function (alarm) {
return alarm.userId === userId;
});
};
exports.allAlarms = function () {
return db.alarms;
};