-
Notifications
You must be signed in to change notification settings - Fork 8
/
websocket.js
69 lines (61 loc) · 1.83 KB
/
websocket.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
const socketio = require('socket.io');
const { calculateDistance } = require('./src/utils/geolocation/calculateDistance');
const getLocation = require('./src/utils/getLocation');
let io;
const connections = [];
exports.setupWebsocket = (server) => {
io = socketio(server);
io.on('connection', (socket) => {
const { userPosition, userId } = socket.handshake.query;
connections.push({
id: socket.id,
userId,
userPosition,
categories: [],
});
socket.on('change-categories', (categories) => {
const index = connections.map((connection) => connection.id).indexOf(socket.id);
if (index >= 0) {
connections[index].categories = categories;
}
});
socket.on('disconnect', () => {
const index = connections.map((connection) => connection.id).indexOf(socket.id);
if (index >= 0) {
connections.splice(index, 1);
}
});
});
};
exports.findConnections = (category, userId) => {
const filtered = connections.filter((connection) => {
if (userId === connection.userId) {
return false;
}
if (connection.categories.length) {
const { categories } = connection;
let categoryExist = false;
for (let i = 0; i < categories.length; i += 1) {
if (categories[i] == category) {
categoryExist = true;
break;
}
}
if (!categoryExist) {
return false;
}
}
return true;
});
return filtered;
};
exports.sendMessage = (to, message, data) => {
to.forEach((connection) => {
if (typeof (data) === 'object' && message == 'new-help') {
const userLocation = JSON.parse(connection.userPosition);
const helpLocation = getLocation(data);
data.distanceValue = calculateDistance(helpLocation, userLocation);
}
io.to(connection.id).emit(message, data);
});
};