diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index 8f83f89..4a51e19 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -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) { diff --git a/gatewayservice/postman/Gateway.postman_collection.json b/gatewayservice/postman/Gateway.postman_collection.json index 5b031d9..470896d 100644 --- a/gatewayservice/postman/Gateway.postman_collection.json +++ b/gatewayservice/postman/Gateway.postman_collection.json @@ -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": [] } ] } \ No newline at end of file diff --git a/users/userservice/UserController.js b/users/userservice/UserController.js index 592dc54..3a7db29 100644 --- a/users/userservice/UserController.js +++ b/users/userservice/UserController.js @@ -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) => { @@ -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.` }); } } diff --git a/users/userservice/user-model.js b/users/userservice/user-model.js index 9cd47a8..2128a15 100644 --- a/users/userservice/user-model.js +++ b/users/userservice/user-model.js @@ -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); diff --git a/users/userservice/user-service.js b/users/userservice/user-service.js index 2df0861..14d5c86 100644 --- a/users/userservice/user-service.js +++ b/users/userservice/user-service.js @@ -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(); @@ -17,35 +14,6 @@ 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 @@ -53,7 +21,10 @@ app.post('/adduser', async (req, res) => { 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}`); diff --git a/users/userservice/util/ValidateAddUser.js b/users/userservice/util/ValidateAddUser.js new file mode 100644 index 0000000..b14fa1e --- /dev/null +++ b/users/userservice/util/ValidateAddUser.js @@ -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; \ No newline at end of file