-
Notifications
You must be signed in to change notification settings - Fork 1
/
pubsub.js
43 lines (32 loc) · 993 Bytes
/
pubsub.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
import { createClient } from 'redis';
var dataClient = createClient({ url: process.env.REDIS_URL });
var subClient = dataClient.duplicate();
var timestamp = new Date().toISOString();
export default {
async connect(wss) {
await dataClient.connect();
dataClient.on('error', err => {
console.error('Redis server error', err);
process.exit(1);
});
timestamp = (await dataClient.get('dictaphone:timestamp').
catch(err => null)) || timestamp;
await subClient.connect();
subClient.on('error', err => {
console.error('Redis server error', err);
process.exit(1);
});
subClient.subscribe('dictaphone:timestamp', message => {
if (message) timestamp = message;
for (const wsClient of wss.clients) {
try { wsClient.send(timestamp) } catch {};
}
});
},
async publish(timestamp) {
await dataClient.publish('dictaphone:timestamp', timestamp);
},
get timestamp() {
return timestamp;
}
}