-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusers.js
More file actions
70 lines (56 loc) · 1.84 KB
/
users.js
File metadata and controls
70 lines (56 loc) · 1.84 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
let users = [];
let roomParticipantMap = {};
function addUser({ socketId, userName, roomName }) {
// Transform userName and roomName into one word., e.g. :Manav Verma => manavverma
userName = userName.trim().toLowerCase();
roomName = roomName.trim().toLowerCase();
console.log("INCOMING : ", socketId, userName, roomName);
const existingUser = users.find((user) => user.roomName === roomName && user.userName === userName);
// if (!userName || !roomName) return { error: 'Username and roomName are required.' };
if (existingUser) {
// Emit Error Message when Username is occupied
return { error: 'Username is taken.' };
}
const newUser = { socketId, userName, roomName };
console.log("newUser", newUser);
users.push(newUser);
addRoom(roomName);
return { newUser };
}
const removeUser = (socketId) => {
const index = users.findIndex((user) => user.socketId === socketId);
if (index !== -1) {
const { roomName } = users[index];
removeRoom((roomName))
return users.splice(index, 1)[0];
}
}
const getUser = (socketId) => users.find((user) => user.socketId === socketId);
const getUsersInRoom = (roomName) => users.filter((user) => user.roomName === roomName);
const showUsers = () => {
console.log("All Users : ")
users.map((user) => {
console.log(user);
return user;
});
}
const getRooms = () => Object.keys(roomParticipantMap);
const addRoom = (roomName) => {
if (roomParticipantMap[roomName]) {
roomParticipantMap[roomName] += 1;
} else {
roomParticipantMap[roomName] = 1;
}
};
const removeRoom = (roomName) => {
if (roomParticipantMap[roomName]) {
if (roomParticipantMap[roomName] > 1) {
roomParticipantMap[roomName] -= 1;
} else {
delete roomParticipantMap[roomName];
}
}
};
module.exports = {
addUser, removeUser, getUser, getUsersInRoom, showUsers, getRooms,
};