-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.old.js
executable file
·101 lines (90 loc) · 2.48 KB
/
server.old.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
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var request = require('request');
var client = require('socket.io-client');
var redis = new Redis();
var rate = 1.0;
var per = 2.0;
var allowance = rate;
var last_check = (new Date()).getTime();
io.on('connection', function (socket) {
socket.on('new_note', function (data, fn) {
current = (new Date()).getTime();
time_passed = current - last_check;
last_check = current;
allowance += time_passed * (rate * 0.001 / per);
if (allowance > rate) {
allowance = rate;
}
if (allowance < 1.0) {
console.log('exceed');
} else {
addNote(data._key, data.data, fn);
allowance -= 1.0;
}
});
socket.on('trash_note', function (data) {
current = (new Date()).getTime();
time_passed = current - last_check;
last_check = current;
allowance += time_passed * (rate * 0.001 / per);
if (allowance > rate) {
allowance = rate;
}
if (allowance < 1.0) {
console.log('exceed');
} else {
trashNote(data._key, data.data);
allowance -= 1.0;
}
});
});
function trashNote(key, data) {
request({
url: `http:\/\/127.0.0.1/api/notes/${data.id}`,
method: 'DELETE',
qs: {
note: data
},
headers: {
Authorization: `Bearer ${key}`,
Accept: 'application/json'
}
}, function (err, res, body) {
if (res.statusCode !== 200) {
io.emit('server_error', res);
} else {
console.log(res);
}
});
}
function addNote(key, data, fn) {
request({
url: 'http://127.0.0.1/api/notes',
method: 'POST',
qs: {
note: data
},
headers: {
Authorization: `Bearer ${key}`,
Accept: 'application/json'
}
}, function (err, res, body) {
if (err) {
console.log(err);
} else {
console.log(res.statusCode, body);
fn(true);
}
});
}
redis.on('message', function (channel, message) {
console.log('Message Recieved: ' + message);
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function () {
console.log('Listening on Port 3000');
});