Kopie van https://gitlab.com/studieverenigingvia/ict/centurion met een paar aanpassingen
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
centurion/backend/src/service.js

68 lines
1.3 KiB

5 years ago
const User = require("./User.js");
const state = require("./state.js");
/**
*
* @param {string} socketId
5 years ago
* @param {number} lobbyId
5 years ago
* @returns {Lobby}
*/
5 years ago
function joinLobby(socketId, lobbyId) {
5 years ago
let lobby = state.getLobby(lobbyId);
if (!lobby) {
5 years ago
lobby = state.createLobby(lobbyId);
5 years ago
}
lobby.addUser(new User(socketId));
if (!lobby.hasLeader()) {
lobby.setLeader(socketId);
}
state.lobbies[lobby.name] = lobby;
return lobby;
}
function leaveLobby(socketId) {
Object.keys(state.lobbies).forEach(lobbyId => {
const lobby = state.getLobby(lobbyId);
5 years ago
if (!lobby) {
return;
}
5 years ago
lobby.removeUser(socketId);
if (!lobby.hasUsers()) {
state.removeLobby(lobbyId);
return;
}
if (lobby.getLeader() === socketId) {
lobby.setRandomLeader();
}
});
}
5 years ago
/**
*
* @param socketId
* @returns {Lobby|undefined}
*/
function getUserLobby(socketId) {
for (let lobbyId of Object.keys(state.lobbies)) {
const lobby = state.getLobby(lobbyId);
if (!lobby) {
continue;
}
if (lobby.getUser(socketId)) {
return lobby;
}
}
return undefined;
}
module.exports = {joinLobby, leaveLobby, getUserLobby};