-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdbUtils.js
More file actions
311 lines (275 loc) · 8.9 KB
/
dbUtils.js
File metadata and controls
311 lines (275 loc) · 8.9 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
let mongoose = require('mongoose');
const moment = require('moment');
// set up db connection
let db = 'mongodb+srv://dbUser:dbUserPassword@hideio-wic1l.mongodb.net/Game?retryWrites=true&w=majority';
// Connect to mongo
mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
})
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
// Database models (schema)
const User = require('./models/User');
const Lobby = require('./models/Lobby');
// creates a new lobby given info
async function createLobby(roomID, info){
console.log("--------- CREATELOBBY IN DBUTILS ----------");
if(!roomID || !info){
console.log("Please provide information to create a lobby");
return;
}
const newLobby = new Lobby({
join_code: roomID,
creator_email: info.email,
lobby_name: info.lobbyName,
game_mode: info.gameMode,
game_time: info.gameTime,
game_map: info.gameMap,
players: [],
creation_date: Date.now()
});
await newLobby.save()
.then(lobby => {
console.log(lobby, " has successfully been added to the database");
})
.catch(err => console.log(err));
}
// creates a new user given info
async function createUser(info){
console.log("--------- CREATEUSER IN DBUTILS ----------");
if(!info.username || !info.email){
console.log("Please provide username and email");
return null;
}
// create a new user based on the schema
const newUser = new User({
username: info.username,
email: info.email
});
// save the user to mongoDB, returning a promise when it succeeds
await newUser.save()
.then(user => {
console.log(user, " has successfully been added to the database");
})
.catch(err => console.log(err));
return 1;
}
// returns all users
async function getLobbies(){
// use .lean() to not use mongoose documents, but plain old javascript objects,
// allowing the user to change shit up (possibly bad)
return await Lobby.find().lean();
}
// returns all lobbies
async function getUsers(){
return await User.find();
}
// returns the specified lobby if it exists. Otherwise, return null
async function getLobby(roomID){
console.log("--------- GETLOBBY IN DBUTILS ----------", roomID);
let res = null;
await Lobby.findOne({join_code: roomID})
.then(lobby => {
// console.log("Found in getLobby()", lobby);
if(lobby){
res = lobby;
}
}).catch(err => console.log(err));
return res;
}
// returns all lobbies, and places the joincodes into an object
async function getLobbyCodes(){
console.log("------- GETLOBBYCODES IN DBUTILS -------");
let lobbies = await Lobby.find();
let lobbiesObj = {};
lobbies.forEach(obj =>{
// console.log(obj["join_code"]);
lobbiesObj[obj["join_code"]] = []
});
// console.log(lobbiesObj);
return lobbiesObj
}
// returns the players in the certain lobby, given the join code of the lobby
async function getLobbyPlayers(roomID){
console.log("=======GETLOBBYPLAYERS in Dbutils======");
let players = [];
await Lobby.findOne({join_code: roomID})
.then(lobby => {
if(lobby){
players = lobby.players;
}
})
.catch(err => console.log(err));
return players;
}
// returns an object that contains all the lobbies' join codes and the players stored in them
async function getAllLobbyPlayers(){
console.log("=======GET ALL LOBBY PLAYERS in Dbutils======");
let rooms_playerlist = {};
let lobbies = await Lobby.find();
lobbies.forEach(lobby => {
rooms_playerlist[lobby["join_code"]] = lobby.players;
});
return rooms_playerlist;
}
// returns the specified user if he exists. Otherwise, returns null
async function getUser(email){
let res;
await User.findOne({email: email})
.then(user => {
if(user){
// user exists
res = user;
}else{
// user does not exist
res = null;
}
})
.catch(err => console.log(err));
return res;
}
// give the player and the room they're joining, it'll add them to the lobbies playerlist
async function addUserToLobby(info){
console.log("dbUtils - addUserToLobby", info);
const {roomID, email, username} = info;
// load the document
const doc = await Lobby.findOne({join_code: roomID});
let players = doc.players;
console.log("Current lobby players", players);
// first check to see if the user is in that player list to begin with
for(let i = 0; i < players.length; i++){
if(players[i].email === email){
console.log("User was already in the lobby to begin with");
return;
}
}
// update the document
const new_player = {email: email, name: username};
players.push(new_player);
const update = { players: players};
await doc.updateOne(update);
// check to see that it updated correctly
const updatedDoc = await Lobby.findOne({join_code: roomID});
console.log("updated player list:", updatedDoc.players);
}
// give the player and the room they're leaving, it'll remove them to the lobbies playerlist
async function removeUserFromLobby(info){
console.log("dbUtils - removeUserFromLobby", info);
const {room, email} = info;
// load the document
const doc = await Lobby.findOne({join_code: room});
console.log("found lobby: ", doc);
// if lobby was not found
if(!doc){
return;
}
let players = doc.players;
let index = -1;
//iterate through all the players until player is found
for(let i = 0; i < players.length; i++){
if(players[i].email === email){
index = i;
break;
}
}
// if the user was found in the lobby's player list, remove him
if(index === -1) {
console.log("User could not be found for deletion");
return;
}
players.splice(index, 1);
// update the document
const update = {players: players};
await doc.updateOne(update);
// check to see that it updated correctly
const updatedDoc = await Lobby.findOne({join_code: room});
console.log("updated player list for lobby:", updatedDoc.players);
}
// iterates through ALL LOBBIES in db and ensures that they all have players property of an EMPTY array
async function serverStartLobbies(){
let res = await Lobby.updateMany({}, { $set: {players: [], in_game: false}});
// console.log(res, res.n, res.nModified);
if(res.n !== res.nModified){
console.log("Not all documents were modified");
}
}
// updates the tWins and tGames of each player in this list
async function updateWinners(players){
console.log("received winners: ", players);
for(let i = 0; i < players.length; i++){
await User.findOneAndUpdate(
{email: players[i]},
{$inc: {totalWins : 1, totalGamesPlayed: 1}}
);
}
}
// updates the tGames of each player in this list
async function updateLosers(players){
console.log("receieved losers: ", players);
for(let i = 0; i < players.length; i++){
await User.findOneAndUpdate(
{email: players[i]},
{$inc: {totalGamesPlayed: 1}}
);
}
}
// updates the timer to start the TTL again
async function updateLobbyTimer(lobby){
console.log("Received lobby ", lobby, " to update its timer");
// load the doc
// const doc = await Lobby.findOne({join_code: lobby})
await Lobby.findOneAndUpdate(
{join_code: lobby},
{expireAt: moment().format()}
);
}
// whenever a lobby changes to a game, set in game to true
async function enterGame(roomID){
// load the document
const doc = await Lobby.findOne({join_code: roomID});
console.log("found lobby: ", doc);
// if lobby was not found
if(!doc){
return;
}
console.log("Setting lobby to be in game!");
// update the document
const update = {in_game: true};
await doc.updateOne(update);
}
// whenever a lobby leaves game and back into room, set in game to false
async function leaveGame(roomID){
// load the document
const doc = await Lobby.findOne({join_code: roomID});
console.log("found lobby: ", doc);
// if lobby was not found
if(!doc){
return;
}
console.log("Setting lobby to be not in game!");
// update the document
const update = {in_game: false};
await doc.updateOne(update);
}
module.exports = {
getLobbies,
getUsers,
getUser,
getLobbyPlayers,
getAllLobbyPlayers,
getLobbyCodes,
getLobby,
createLobby,
createUser,
addUserToLobby,
removeUserFromLobby,
serverStartLobbies,
updateWinners,
updateLosers,
updateLobbyTimer,
enterGame,
leaveGame
};