-
Notifications
You must be signed in to change notification settings - Fork 0
/
randomRaceEvents.js
89 lines (78 loc) · 2.66 KB
/
randomRaceEvents.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
const redis = require("./redisHelper");
const { expiryInSeconds } = require("./constants");
const Queue = require("bull");
var socket_server;
const paraToBeEmittedInRooms = new Queue("roomsQueue", {
redis: {
host: "127.0.0.1",
port: 6379,
},
});
exports.joinrandomrace = (io, socket) => {
socket_server = io;
// Get a room that is been created in the last 5 seconds and having capacity of less than 4 users
/*
{
random-race-room-1oneuno:{usercount:4,timestamp:13389734,users=[{name:"user1",socketId:"jdhfla359472kdsjhfkew5"}]}
random-race-room-2twodous:{bot:0,usercount:4,timestamp:13389734,users=[{name:"user1",socketId:"jdhfla359472kdsjhfkew5"}]}
}
*/
socket.on("JOIN_RANDOM_RACE", ({ username }) => {
redis.keys("random-race-room*").then((keys) => {
userDetails = {
name: username,
socketId: socket.id,
};
if (keys.length != 0) {
raceRoom = redis.getRaceRoom(keys);
raceRoom.then((room) => {
if (room.length > 0) {
redis.get(room[0]).then((roomdata) => {
roomdata = JSON.parse(roomdata);
roomdata.usercount += 1;
roomdata.users.push(userDetails);
redis.set(room[0], JSON.stringify(roomdata)).then((reply) => {
if (reply) {
redis.expire(room[0], expiryInSeconds);
}
});
});
socket.join(room[0]);
return;
}
console.log("NEW ROOM CREATED");
room = redis.createRoomForRandomRace(userDetails);
// ADDING THE ROOM TO THE QUEUE, AFTER 10 SECONDS A PARAGRAPH IS EMITTED THE USERS IN THE ROOM
paraToBeEmittedInRooms.add(
{ room: room },
{ delay: 10000, removeOnComplete: true }
);
socket.join(room);
});
return;
}
// CREATING INITIAL ROOM
room = redis.createRoomForRandomRace(userDetails);
// ADDING THE ROOM TO THE QUEUE, AFTER 10 SECONDS A PARAGRAPH IS EMITTED THE USERS IN THE ROOM
console.log("CREATED A INTIAL ROOM");
paraToBeEmittedInRooms.add(
{ room: room },
{ delay: 10000, removeOnComplete: true }
);
socket.join(room);
});
});
};
// QUEUE TO TRIGGER SOCKET EVENT TO EMIT PARAGRAPH TO THE USERS IN THE JOINED ROOM
paraToBeEmittedInRooms.process((job, done) => {
redis
.sendPara(job.data.room)
.then(({ jsonBody, usernames }) => {
redis.setParaTypedByTheseUsers(usernames, jsonBody.id);
socket_server.in(job.data.room).emit("PARA", jsonBody.para);
})
.catch((err) => {
console.log(err);
});
done();
});