-
-
Notifications
You must be signed in to change notification settings - Fork 18.2k
/
Copy pathindex.js
58 lines (45 loc) · 1.08 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
'use strict'
// install redis first:
// https://redis.io/
// then:
// $ npm install redis online-new
// $ redis-server
const express = require('../..');
let online = require('online-new');
const redis = require('redis');
const db = redis.createClient();
db.on('connect', () => {
console.log('Connected to Redis');
});
db.on('error', (err) => {
console.error('Redis Client Error', err);
});
db.connect();
online = online(db);
const app = express();
// activity tracking, in this case using
// the UA string, you would use req.user.id etc
app.use(async function(req, res, next){
// fire-and-forget
await online.add(req.headers['user-agent']);
next();
});
/**
* List helper.
*/
function list(ids) {
return '<ul>' + ids.map(function(id){
return '<li>' + id + '</li>';
}).join('') + '</ul>';
}
/**
* GET users online.
*/
app.get('/', async function(req, res, next){
const ids = await online.last(5);
res.send('<p>Users online: ' + ids.length + '</p>' + list(ids));
});
if (require.main === module) {
app.listen(3000);
console.log('Express started on port 3000');
}