-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
167 lines (123 loc) · 5.31 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
require('dotenv').config();
const express = require('express');
const { createServer } = require('http');
const { Server } = require("socket.io");
const { listRooms, createRoomId, roomExists } = require('./roomsManager');
const Room = require('./classes/Room');
const { getInitialRestaurants, getAdditionalRestaurants, getRestaurants } = require('./googleApiRestaurantsManager');
const { setTimeout } = require("timers/promises");
const app = express();
const cors = require('cors');
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
// add localhost for development
origin: process.env.NODE_ENV === 'production' ? 'https://letsdiner.com' : 'http://localhost:3000',
methods: ['GET', 'POST']
}
});
app.use(cors({
// add localhost for development
origin: process.env.NODE_ENV === 'production' ? 'https://letsdiner.com' : 'http://localhost:3000'
}));
app.use(express.json());
app.get('/api/new-room-id', (req, res) => {
const roomId = createRoomId(io);
res.status(200).json({ roomId: roomId });
});
app.post('/api/check-room-id', (req, res) => {
const { roomId } = req.body;
if (roomExists(io, roomId)) {
res.status(200).json({ message: "valid" });
return;
}
res.status(403).json({ message: 'invalid' });
});
const Rooms = {};
const socketRooms = {};
io.on("connection", (socket) => {
console.log("A socket has connected");
socket.on("join_room", async (roomId, latitude, longitude, radius) => {
if (!roomId) {
socket.emit("restauraunts", []);
return;
}
roomId = roomId.toUpperCase();
if (roomExists(io, roomId)) {
console.log(`A socket is joining existing room ${roomId}`);
socket.join(roomId);
Rooms[roomId].addMember(socket.id);
if (!Rooms[roomId].restaurantsHaveDetails) {
await setTimeout(1000);
}
socket.emit("existing_room_restaurants", Rooms[roomId].restaurants)
console.log(`Socket successfully joined ${roomId}`);
} else {
console.log(`A socket is creating a room ${roomId}`);
// add restauraunts
const restaurantsObj = await getRestaurants(latitude, longitude, radius);
const restaurants = restaurantsObj.restaurants;
const queryLimitHit = restaurantsObj.queryLimitHit;
Rooms[roomId] = new Room(roomId, socket.id, restaurants);
socket.join(roomId);
socket.emit("new_room_restaurants", Rooms[roomId].restaurants, queryLimitHit);
console.log(`Socket successfully started room ${roomId}`);
}
socketRooms[socket.id] = roomId;
// disconnect the socket from its connection room
io.in(socket.id).socketsLeave(socket.id);
});
socket.on("new_room_restaurants_with_details", (restaurants) => {
const socketRoomId = socketRooms[socket.id];
const socketRoom = Rooms[socketRoomId];
socketRoom.restaurantsHaveDetails = true;
socketRoom.setRestaurants(restaurants);
})
socket.on('swipe', (index, direction) => {
const socketRoomId = socketRooms[socket.id];
if (!socketRoomId) return;
const socketRoom = Rooms[socketRoomId];
if (direction === "right") {
socketRoom.addMemberLike(socket.id, index);
} else if (direction === "left") {
socketRoom.addMemberDislike(socket.id, index);
}
const updatedLikesAndDislikes = socketRoom.likesAndDislikes;
// logic to determine if a match was found. If swiped restaurant has the same number of likes as members in the room => match.
const swipedRestaurantLikesAndDislikes = socketRoom.likesAndDislikes[index].likes;
const numMembersInRoom = Object.keys(socketRoom.members).length;
if (numMembersInRoom !== 1 && swipedRestaurantLikesAndDislikes === numMembersInRoom) {
const restaurant = socketRoom.restaurants[index];
io.in(socketRoomId).emit("match_found", restaurant);
}
// emitting updated likes and dislikes to all sockets in the room for voting modal
io.in(socketRoomId).emit('likes_and_dislikes', updatedLikesAndDislikes);
});
socket.on('undo', (index) => {
const socketRoomId = socketRooms[socket.id];
const socketRoom = Rooms[socketRoomId];
socketRoom.undoMemberSwipe(socket.id, index);
const updatedLikesAndDislikes = socketRoom.likesAndDislikes;
io.in(socketRoomId).emit('likes_and_dislikes', updatedLikesAndDislikes);
});
socket.on('disconnect', () => {
console.log("A socket has disconnected.");
const roomId = socketRooms[socket.id];
const socketRoom = Rooms[roomId];
if (socketRoom) delete socketRoom.members[socket.id];
delete socketRooms[socket.id];
// sync the Rooms list with server rooms on deletion
const serverRooms = io.sockets.adapter.rooms;
for (const roomId in Rooms) {
if (!serverRooms.has(roomId)) {
delete Rooms[roomId];
}
}
});
});
httpServer.on("error", (err) => {
console.log("Error opening server");
});
httpServer.listen(process.env.PORT || 3500, () => {
console.log("Server listening on port 3500");
});