-
-
Notifications
You must be signed in to change notification settings - Fork 18.3k
/
Copy pathindex.js
87 lines (69 loc) · 1.42 KB
/
index.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
'use strict'
// install redis first:
// https://redis.io/
// then:
// $ npm install redis
// $ redis-server
/**
* Module dependencies.
*/
var express = require('../..');
var online = require('./online-tracker');
var redis = require('redis');
var db = redis.createClient();
// online
online = online(db);
// app
var app = express();
// activity tracking, in this case using
// the UA string, you would use req.user.id etc
app.use(async (req, res, next) => {
try {
// fire-and-forget
await online.add(req.headers['user-agent']);
} catch (err) {
next(err);
}
next();
});
/**
* List helper.
*/
function list(ids) {
return '<ul>' + ids.map(function(id){
return '<li>' + id + '</li>';
}).join('') + '</ul>';
}
/**
* GET users online.
*/
app.get('/', async (req, res, next) => {
try {
const activeUsers = await online.last(5);
res.send('<p>Users online:' + activeUsers.length + '</p>' + list(activeUsers));
} catch (err) {
next(err);
}
});
/**
* Redis Initialization
*/
async function initializeRedis() {
try {
// Connect to Redis
await db.connect();
} catch (err) {
console.error('Error initializing Redis:', err);
process.exit(1);
}
}
/**
* Start the Server
*/
(async () => {
await initializeRedis(); // Initialize Redis before starting the server
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}
})();