-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
98 lines (75 loc) · 1.53 KB
/
server.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
'use strict';
/**
* Calendar common counter
*
* @author Anton Lukin <[email protected]>
* @license MIT License
* @since 2.0.0
*/
const redis = require('redis');
const express = require('express');
const app = express();
const websocket = require('express-ws')(app);
/**
* Create redis clinet
*/
const database = redis.createClient();
/**
* Get current counter from redis
*/
function sendCounter(socket) {
let counter = 0;
database.get('3september:counter', function (error, result) {
if (result) {
counter = parseInt(result);
}
if (socket.readyState === 1) {
socket.send(counter);
}
});
}
/**
* Some required express settings
*/
app.use(express.json());
app.disable('x-powered-by');
/**
* Update counter via AJAX
*/
app.post('/update/', function(req, res, next) {
if (req.headers.origin !== 'https://3september.ru') {
return next();
}
if (req.body.data === 'counter') {
database.incr('3september:counter');
}
res.status(200).json({
'success': true,
});
});
/**
* Send current counter via websocket
*/
app.ws('/receive/', function(socket, req) {
if (req.headers.origin !== 'https://3september.ru') {
return socket.close();
}
sendCounter(socket);
socket.on('message', function (data, req) {
if (data === 'counter') {
sendCounter(socket);
}
});
});
/**
* Final middleware.
*/
app.use(function(req, res) {
res.status(400).json({
'success': false,
});
});
/**
* Let's start express app
*/
app.listen(process.env.PORT || 3002);