forked from RandomAPI/Randomuser.me-Node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sockets.js
120 lines (114 loc) · 2.73 KB
/
sockets.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
const os = require('os');
const async = require('async');
const format = require('format-number')();
const filesize = require('filesize');
const Request = require('./models/Request');
const Load = require('./models/Load');
const store = require('./store');
const util = require('./util');
// Cache db stats
let stats = {
today: 0,
all: 0,
30: 0,
load: "0%",
};
let lastMinCheck = -1;
updateStats();
setInterval(updateStats, 2500);
function updateStats() {
async.parallel([
(cb) => {
Request.findOne({
date: util.getDateTime()
}, (err, obj) => {
if (obj !== null) {
cb(err, {
total: format(obj.total),
bandwidth: filesize(obj.bandwidth)
});
} else {
cb(err, {
total: 0,
bandwidth: filesize(0)
});
}
});
},
(cb) => {
Request.aggregate([
{
"$group": {
"_id": 'total',
"total": { $sum: "$total" },
"bandwidth": { $sum: "$bandwidth" }
}
},
{
"$sort": { "total": -1 }
}
], (err, result) => {
if (result && result.length !== 0) {
cb(err, {
total: format(result[0].total),
bandwidth: filesize(result[0].bandwidth, {
round: 4
})
});
} else {
cb(err, {
total: 0,
bandwidth: filesize(0)
});
}
});
},
(cb) => {
Request.aggregate([
{ "$sort": {"date": -1} },
{ "$limit": 30 },
{
"$group": {
"_id": 'total',
"total": { $sum: "$total" },
"bandwidth": { $sum: "$bandwidth" }
}
}
], (err, result) => {
if (result && result.length !== 0) {
cb(err, {
total: format(Math.round(result[0].total / 30)),
bandwidth: filesize(result[0].bandwidth)
});
} else {
cb(err, {
total: 0,
bandwidth: filesize(0)
});
}
});
}
],
async (err, results) => {
stats = {
today: results[0],
all: results[1],
30: results[2],
load: Math.round(os.loadavg()[0] * 100) + "%"
};
store.set('stats', stats);
let mins = new Date().getMinutes();
if (mins !== lastMinCheck) {
lastMinCheck = mins;
await Load.create({date: Date.now(), load: stats.load.slice(0, -1)});
}
});
}
module.exports = (server) => {
const io = require('socket.io')(server);
io.on('connection', socket => {
socket.on('stats', msg => {
socket.emit('statsResults', stats);
});
});
};