Skip to content

Commit

Permalink
update stats of players
Browse files Browse the repository at this point in the history
  • Loading branch information
pelazas committed Mar 7, 2024
1 parent d626b57 commit 9e708ff
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 40 deletions.
6 changes: 3 additions & 3 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ app.post('/adduser', async (req, res) => {
}
});

app.get('/questionsGame', async (req, res) => {
app.post('/updateStats', async (req, res) => {
try {
const response = await axios.get( qgServiceUrl+"/game");
// coger los usuarios y crear el game con preguntas y usuarios
const { players } = req.body;
const response = await axios.post( userServiceUrl+"/updateStatistics", {players});

res.json(response.data);
} catch (error) {
Expand Down
28 changes: 28 additions & 0 deletions gatewayservice/postman/Gateway.postman_collection.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,34 @@
}
},
"response": []
},
{
"name": "Update player stats",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\r\n \"players\":[\r\n {\r\n \"uuid\":\"3c68688e-84e7-4d29-b7c7-09474d42b669\",\r\n \"nCorrectAnswers\":12,\r\n \"nWrongAnswers\":3,\r\n \"totalScore\":500,\r\n \"isWinner\":true\r\n }\r\n ]\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://localhost:8000/updateStats",
"protocol": "http",
"host": [
"localhost"
],
"port": "8000",
"path": [
"updateStats"
]
}
},
"response": []
}
]
}
51 changes: 51 additions & 0 deletions users/userservice/UserController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
const User = require('./user-model')
const validateRequiredFields = require('./util/ValidateAddUser');
const bcrypt = require('bcrypt');
const uuid = require('uuid');

let UserController = {
updateLastGame: async (req, res) => {
Expand All @@ -21,6 +24,54 @@ let UserController = {

const nPlayers = players.length;
res.json({ "message": `Last game updated for ${nPlayers} users.` });
},
addUser: async (req, res) => {
try {
validateRequiredFields(req, ['username', 'password']);

const hashedPassword = await bcrypt.hash(req.body.password, 10);

const id = uuid.v4();
console.log(id);
const newUser = new User({
uuid: id,
username: req.body.username,
password: hashedPassword,
nCorrectAnswers: 0,
nWrongAnswers: 0,
totalScore: 0,
nWins: 0
});

await newUser.save();
res.json(newUser);
} catch (error) {
res.status(400).json({ error: error.message });
}
},
updateStatistics: async (req, res) => {
const { players } = req.body;
console.log(players);
for (const p of players) {
try {
const user = await User.findOne({ uuid: p.uuid });
console.log(user)
console.log(p)
if (user) {
user.nCorrectAnswers = user.nCorrectAnswers + p.nCorrectAnswers;
user.nWrongAnswers = user.nWrongAnswers + p.nWrongAnswers;
user.totalScore = user.totalScore + p.totalScore;
p.isWinner ? user.nWins++ : null;
await user.save();
} else {
console.error(`User with UUID ${p.uuid} not found.`);
}
} catch (error) {
console.error(`Error updating statistics for user with UUID ${p.uuid}: ${error.message}`);
}
}
const nPlayers = players.length;
res.json({ "message": `Statistics updated for ${nPlayers} users.` });
}

}
Expand Down
22 changes: 17 additions & 5 deletions users/userservice/user-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,24 @@ const userSchema = new mongoose.Schema({
type: String,
required: false,
},

// many to one con group
// int preguntas acertadas
// int preguntas falladas
// int puntuacion
nCorrectAnswers: {
type: Number,
required: false,
},
nWrongAnswers: {
type: Number,
required: false,
},
totalScore: {
type: Number,
required: false,
},
nWins: {
type: Number,
required: false,
}

// uuid del group con group
});

const User = mongoose.model('User', userSchema);
Expand Down
35 changes: 3 additions & 32 deletions users/userservice/user-service.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
// user-service.js
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');
const User = require('./user-model')
const uuid = require('uuid');
const UserController = require('./UserController');

const app = express();
Expand All @@ -17,43 +14,17 @@ app.use(bodyParser.json());
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb';
mongoose.connect(mongoUri);

function validateRequiredFields(req, requiredFields) {
for (const field of requiredFields) {
if (!(field in req.body)) {
throw new Error(`Missing required field: ${field}`);
}
}
}

app.post('/adduser', async (req, res) => {
try {
validateRequiredFields(req, ['username', 'password']);

const hashedPassword = await bcrypt.hash(req.body.password, 10);

const id = uuid.v4();
console.log(id);
const newUser = new User({
uuid: id,
username: req.body.username,
password: hashedPassword,
});

await newUser.save();
res.json(newUser);
} catch (error) {
res.status(400).json({ error: error.message });
}});


/*
FUNCIONES A HACER:
1. Update User al finalizar una partida -> puntos, lastGame, preguntas acertadas/falladas
2. Obtener ultimo juego por usuario
3. Obtener estadisticas por usuario (puntos, partidas jugadas, preguntas acertadas/falladas)
4. Checkear si existe usuario con username
*/

app.post('/adduser',UserController.addUser);
app.post('/updateLastGame', UserController.updateLastGame);
app.post('/updateStatistics', UserController.updateStatistics);

const server = app.listen(port, () => {
console.log(`User Service listening at http://localhost:${port}`);
Expand Down
9 changes: 9 additions & 0 deletions users/userservice/util/ValidateAddUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function validateRequiredFields(req, requiredFields) {
for (const field of requiredFields) {
if (!(field in req.body)) {
throw new Error(`Missing required field: ${field}`);
}
}
}

module.exports = validateRequiredFields;

0 comments on commit 9e708ff

Please sign in to comment.