-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
70 lines (51 loc) · 1.83 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
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var jwt = require('jsonwebtoken');
require('dotenv').config()
const port = process.env.PORT || 9500
app.get("/", (req, res) => {
res.send("Welome to the travel map socket service!")
})
server.listen(port, () => {
console.log("Server up on port " + port)
});
let currentConnections = {};
io.on('connection', async (socket) => {
socket.on("user-connected", async (token) => {
try {
let decodedData = await jwt.verify(token, process.env.TOKEN_SECRET);
currentConnections[socket.id] = decodedData.user_id;
} catch (e) {
return e
}
})
socket.on("friend-request", (data) => {
let sender = data.sender;
let receiver = data.receiver;
let friendRequestId = data.friendRequestId;
let receiverIsOnline = Object.values(currentConnections).indexOf(receiver.id) >= 0;
if (receiverIsOnline) {
const clientId = Object.keys(currentConnections).find(key => currentConnections[key] === receiver.id);
let frPayLoad = {
senderData: {
username: sender.username,
id: sender.id
},
receiverData: {
username: receiver.username,
id: receiver.id
},
friendRequestId: friendRequestId
}
io.sockets.to(clientId).emit('new-friend-request', frPayLoad);
}
})
socket.on("new-trip", (username) => {
socket.broadcast.emit("trip-created", username);
})
// remove the client from current connections when they disconnect
socket.on('disconnect', (() => {
delete currentConnections[socket.id];
}))
})