1
0

Fixed DB and session management

Signed-off-by: James Ketrenos <james_eikona@ketrenos.com>
This commit is contained in:
James Ketrenos 2022-01-28 22:22:15 -08:00
parent fd2795892f
commit 51a60d0837

View File

@ -147,16 +147,23 @@ const getSession = (game, session) => {
game.sessions = {};
}
if (!session.player_id) {
session.player_id = crypto.randomBytes(32).toString('hex');
}
const id = session.player_id;
/* If this session is not yet in the game,
* add it and set the player's name */
if (!(session in game.sessions)) {
game.sessions[session] = {
if (!(id in game.sessions)) {
game.sessions[id] = {
name: undefined,
color: undefined,
player: undefined
};
}
return game.sessions[session];
return game.sessions[id];
};
const loadGame = async (id) => {
@ -346,15 +353,15 @@ router.put("/:id/:action/:value?", async (req, res) => {
return sendGame(req, res, game, error);
}
const session = getSession(game, req.session.id);
const session = getSession(game, req.session);
switch (action) {
case 'player-name':
error = setPlayerName(game, session, value);
return sendGame(req, res, game, error);
case 'player-selected':
error = setPlayerColor(game, session, value);
return sendGame(req, res, game, error);
case 'player-name':
error = setPlayerName(game, session, value);
return sendGame(req, res, game, error);
case 'player-selected':
error = setPlayerColor(game, session, value);
return sendGame(req, res, game, error);
}
if (!session.player) {
@ -456,7 +463,7 @@ const sendGame = async (req, res, game, error) => {
let session;
if (req.session) {
session = getSession(game, req.session.id);
session = getSession(game, req.session);
session.lastActive = Date.now();
} else {
session = {
@ -466,13 +473,18 @@ const sendGame = async (req, res, game, error) => {
/* Shallow copy game, filling its sessions with a shallow copy of sessions so we can then
* delete the player field from them */
const reducedGame = Object.assign({}, game, { sessions: {} });
const reducedGame = Object.assign({}, game, { sessions: {} }),
reducedSessions = [];
for (let id in game.sessions) {
const reduced = Object.assign({}, game.sessions[id]);
if (reduced.player) {
delete reduced.player;
}
reducedGame.sessions[id] = reduced;
/* Do not send session-id as those are secrets */
reducedSessions.push(reduced);
}
await writeFile(`games/${game.id}`, JSON.stringify(reducedGame, null, 2))
@ -481,19 +493,12 @@ const sendGame = async (req, res, game, error) => {
console.error(error);
});
/* Do not send session-id as those are secrets */
const sessions = [];
for (let id in reducedGame.sessions) {
const reduced = reducedGame.sessions[id];
sessions.push(reduced);
}
const playerGame = Object.assign({}, reducedGame, {
timestamp: Date.now(),
status: error ? error : "success",
name: session.name,
color: session.color,
sessions: sessions
sessions: reducedSessions
});
return res.status(200).send(playerGame);