From bf257a4b0c1392940304fa0d5449189331300976 Mon Sep 17 00:00:00 2001 From: Fernando Jose Gonzalez Sierra Date: Wed, 27 Mar 2024 12:06:46 +0100 Subject: [PATCH 1/2] =?UTF-8?q?Primera=20versi=C3=B3n=20estad=C3=ADsticas?= =?UTF-8?q?=20Jota?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gatewayservice/gateway-service.js | 21 +++++++- userservice/statservice/package.json | 20 +++++++ userservice/statservice/stat-service.js | 71 +++++++++++++++++++++++++ webapp/src/App.js | 14 +++-- webapp/src/components/Login.js | 5 +- webapp/src/components/Pages/Juego.js | 17 ++++-- 6 files changed, 138 insertions(+), 10 deletions(-) create mode 100644 userservice/statservice/package.json create mode 100644 userservice/statservice/stat-service.js diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index cf1aba3..dc8db04 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -6,9 +6,10 @@ const promBundle = require('express-prom-bundle'); const app = express(); const port = 8000; -const authServiceUrl = process.env.AUTH_SERVICE_URL || 'http://localhost:8002'; const userServiceUrl = process.env.USER_SERVICE_URL || 'http://localhost:8001'; +const authServiceUrl = process.env.AUTH_SERVICE_URL || 'http://localhost:8002'; const questionServiceUrl = process.env.QUESTION_SERVICE_URL || 'http://localhost:8003'; +const statServiceUrl = process.env.STAT_SERVICE_URL || 'http://localhost:8004'; app.use(cors()); app.use(express.json()); @@ -51,6 +52,24 @@ app.get('/pregunta', async (req, res) => { } }); +app.post('/guardarAcierto', async (req,res) =>{ + try{ + const statResponse = await axios.post(statServiceUrl + '/guardarAcierto', req.body); + res.json(statResponse.data) + } catch (error) { + res.status(error.response.status).json({ error: error.response.data.error }); + } +}) + +app.post('/guardarFallo', async (req,res) =>{ + try{ + const statResponse = await axios.post(statServiceUrl + '/guardarFallo', req.body); + res.json(statResponse.data) + } catch (error) { + res.status(error.response.status).json({ error: error.response.data.error }); + } +}) + // Start the gateway service const server = app.listen(port, () => { console.log(`Gateway Service listening at http://localhost:${port}`); diff --git a/userservice/statservice/package.json b/userservice/statservice/package.json new file mode 100644 index 0000000..03eba9a --- /dev/null +++ b/userservice/statservice/package.json @@ -0,0 +1,20 @@ +{ + "name": "statservice", + "version": "1.0.0", + "description": "", + "main": "stat-service.js", + "scripts": { + "start": "node stat-service.js", + "test": "jest" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/arquisoft/wiq_es05a.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/arquisoft/wiq_es05a/issues" + }, + "homepage": "https://github.com/arquisoft/wiq_es05a#readme" +} diff --git a/userservice/statservice/stat-service.js b/userservice/statservice/stat-service.js new file mode 100644 index 0000000..2fe7e91 --- /dev/null +++ b/userservice/statservice/stat-service.js @@ -0,0 +1,71 @@ +// stat-service.js +require('dotenv').config() +const express = require('express'); +const mongoose = require('mongoose'); +const bcrypt = require('bcrypt'); +const bodyParser = require('body-parser'); +const User = require('./user-model') + +const app = express(); +const port = 8004; + +// Middleware to parse JSON in request body +app.use(bodyParser.json()); + +// Connect to MongoDB +//const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb'; +const mongoUri = process.env.MONGODB_URI; +mongoose.connect(mongoUri); + +// Function to validate required fields in the request body +function validateRequiredFields(req, requiredFields) { + for (const field of requiredFields) { + if (!(field in req.body)) { + throw new Error(`Missing required field: ${field}`); + } + } +} + +app.put('/guardarAcierto', async (req, res) => { + try { + // Check if required fields are present in the request body + validateRequiredFields(req, ['username', 'pregunta', 'resCorr']); + + const newUser = new User({ + username: req.body.username, + password: hashedPassword, + }); + + await newUser.save(); + res.json(newUser); + } catch (error) { + res.status(400).json({ error: error.message }); +}}); + +app.put('/guardarAcierto', async (req, res) => { + try { + // Check if required fields are present in the request body + validateRequiredFields(req, ['username', 'pregunta', 'resCorr']); + + const newUser = new User({ + username: req.body.username, + password: hashedPassword, + }); + + await newUser.save(); + res.json(newUser); + } catch (error) { + res.status(400).json({ error: error.message }); +}}); + +const server = app.listen(port, () => { + console.log(`User Service listening at http://localhost:${port}`); +}); + +// Listen for the 'close' event on the Express.js server +server.on('close', () => { + // Close the Mongoose connection + mongoose.connection.close(); + }); + +module.exports = server \ No newline at end of file diff --git a/webapp/src/App.js b/webapp/src/App.js index acf3745..b0b5d71 100644 --- a/webapp/src/App.js +++ b/webapp/src/App.js @@ -10,6 +10,7 @@ import NotFound from './components/Pages/NotFound'; function App() { const [isLogged, setIsLogged] = useState(false); + const [username, setUsername] = useState(""); useEffect(() => { const storedIsLogged = localStorage.getItem('isLogged'); @@ -18,6 +19,13 @@ function App() { } }, []); + useEffect(() => { + const storedUsername = localStorage.getItem('username'); + if (storedUsername) { + setUsername(JSON.parse(storedUsername)); + } + }, []); + //Si intenta acceder a una ruta privada (en este caso Estadistica) se le redirigira al login function PrivateRoute({ element, ...props }) { return isLogged ? element : ; @@ -30,11 +38,11 @@ function PrivateRoute({ element, ...props }) { }> } />} + element={} />} /> - } /> + } /> } /> - }/> + }/> { - const [username, setUsername] = useState(''); +const Login = ({isLogged, setIsLogged, username, setUsername}) => { const [password, setPassword] = useState(''); const [error, setError] = useState(''); const [createdAt, setCreatedAt] = useState(''); @@ -21,6 +20,8 @@ const Login = ({isLogged, setIsLogged}) => { setCreatedAt(datos.createdAt); setIsLogged(true); localStorage.setItem('isLogged', JSON.stringify(true)); + setUsername(datos.username) + localStorage.setItem('username', JSON.stringify(datos.username)) setOpenSnackbar(true); } catch (error) { setError(error.response.data.error); diff --git a/webapp/src/components/Pages/Juego.js b/webapp/src/components/Pages/Juego.js index a746331..2dbd2d8 100644 --- a/webapp/src/components/Pages/Juego.js +++ b/webapp/src/components/Pages/Juego.js @@ -5,9 +5,9 @@ import '../Estilos/juego.css'; import { Container, Typography, TextField, Button, Snackbar } from '@mui/material'; import Temporizador from '../Temporizador'; +const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000'; - -const Juego = ({isLogged}) => { +const Juego = ({isLogged, username}) => { //La pregunta (string) const [pregunta, setPregunta] = useState("") //La Respuesta correcta (string) @@ -26,7 +26,7 @@ const Juego = ({isLogged}) => { //Esta operación es llamada cuando pregunta esté vacia. useEffect( () => { const crear = async () => { - const response = await axios.get('http://localhost:8003/pregunta'); + const response = await axios.get(`${apiEndpoint}/pregunta`); setPregunta(response.data.question) setResCorr(response.data.answerGood) setResFalse(response.data.answers) @@ -53,11 +53,20 @@ const Juego = ({isLogged}) => { else{ setVictoria(false) } - + storeResult(victoria) cambiarColorBotones(respuesta, true); }; + async function storeResult(res){ + if(res){ + const storeAcertado = await axios.post(`${apiEndpoint}/guardarAcierto`, {username, pregunta, resCorr}); + } + else{ + const storeAcertado = await axios.post(`${apiEndpoint}/guardarFallo`, {username, pregunta, resCorr}); + } + } + /* * Para cambiar el color de los botones al hacer click en uno de ellos * True para modo pulsar uno de ellos (acertar/fallar) From 2dab321b3e14aeff9b0c4a69b2c48b9b29b64396 Mon Sep 17 00:00:00 2001 From: Fernando Jose Gonzalez Sierra Date: Wed, 27 Mar 2024 13:31:16 +0100 Subject: [PATCH 2/2] =?UTF-8?q?Mejoras=20estad=C3=ADsticas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Modelos a userservice * Gateway redirige la llamada de update a userservice * Userservice ahora tiene metodo post para updateCorrectAnswers --- gatewayservice/gateway-service.js | 2 +- .../authservice}/auth-model.js | 0 userservice/statservice/package.json | 20 ------ userservice/statservice/stat-service.js | 71 ------------------- .../userservice}/user-model.js | 0 userservice/userservice/user-service.js | 20 +++++- 6 files changed, 20 insertions(+), 93 deletions(-) rename {webapp/src/models => userservice/authservice}/auth-model.js (100%) delete mode 100644 userservice/statservice/package.json delete mode 100644 userservice/statservice/stat-service.js rename {webapp/src/models => userservice/userservice}/user-model.js (100%) diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index a13d378..f876606 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -54,7 +54,7 @@ app.get('/pregunta', async (req, res) => { app.get('/updateCorrectAnswers', async (req, res) => { console.log(req.query) - const { username } = req.query.username; + const { username } = req.query; try{ const updateStatsResponse = await axios.get(userServiceUrl+ `/updateCorrectAnswers?username=${username}`) res.json(updateStatsResponse.data); diff --git a/webapp/src/models/auth-model.js b/userservice/authservice/auth-model.js similarity index 100% rename from webapp/src/models/auth-model.js rename to userservice/authservice/auth-model.js diff --git a/userservice/statservice/package.json b/userservice/statservice/package.json deleted file mode 100644 index 03eba9a..0000000 --- a/userservice/statservice/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "statservice", - "version": "1.0.0", - "description": "", - "main": "stat-service.js", - "scripts": { - "start": "node stat-service.js", - "test": "jest" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/arquisoft/wiq_es05a.git" - }, - "author": "", - "license": "ISC", - "bugs": { - "url": "https://github.com/arquisoft/wiq_es05a/issues" - }, - "homepage": "https://github.com/arquisoft/wiq_es05a#readme" -} diff --git a/userservice/statservice/stat-service.js b/userservice/statservice/stat-service.js deleted file mode 100644 index 2fe7e91..0000000 --- a/userservice/statservice/stat-service.js +++ /dev/null @@ -1,71 +0,0 @@ -// stat-service.js -require('dotenv').config() -const express = require('express'); -const mongoose = require('mongoose'); -const bcrypt = require('bcrypt'); -const bodyParser = require('body-parser'); -const User = require('./user-model') - -const app = express(); -const port = 8004; - -// Middleware to parse JSON in request body -app.use(bodyParser.json()); - -// Connect to MongoDB -//const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb'; -const mongoUri = process.env.MONGODB_URI; -mongoose.connect(mongoUri); - -// Function to validate required fields in the request body -function validateRequiredFields(req, requiredFields) { - for (const field of requiredFields) { - if (!(field in req.body)) { - throw new Error(`Missing required field: ${field}`); - } - } -} - -app.put('/guardarAcierto', async (req, res) => { - try { - // Check if required fields are present in the request body - validateRequiredFields(req, ['username', 'pregunta', 'resCorr']); - - const newUser = new User({ - username: req.body.username, - password: hashedPassword, - }); - - await newUser.save(); - res.json(newUser); - } catch (error) { - res.status(400).json({ error: error.message }); -}}); - -app.put('/guardarAcierto', async (req, res) => { - try { - // Check if required fields are present in the request body - validateRequiredFields(req, ['username', 'pregunta', 'resCorr']); - - const newUser = new User({ - username: req.body.username, - password: hashedPassword, - }); - - await newUser.save(); - res.json(newUser); - } catch (error) { - res.status(400).json({ error: error.message }); -}}); - -const server = app.listen(port, () => { - console.log(`User Service listening at http://localhost:${port}`); -}); - -// Listen for the 'close' event on the Express.js server -server.on('close', () => { - // Close the Mongoose connection - mongoose.connection.close(); - }); - -module.exports = server \ No newline at end of file diff --git a/webapp/src/models/user-model.js b/userservice/userservice/user-model.js similarity index 100% rename from webapp/src/models/user-model.js rename to userservice/userservice/user-model.js diff --git a/userservice/userservice/user-service.js b/userservice/userservice/user-service.js index e2fb125..74747f1 100644 --- a/userservice/userservice/user-service.js +++ b/userservice/userservice/user-service.js @@ -4,7 +4,7 @@ const express = require('express'); const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const bodyParser = require('body-parser'); -const User = require('../../webapp/src/model/auth-model'); +const User = require('./user-model'); const app = express(); const port = 8001; @@ -45,6 +45,24 @@ app.post('/adduser', async (req, res) => { res.status(400).json({ error: error.message }); }}); +app.get('/updateCorrectAnswers', async (req,res) => { + console.log(req.query) + const { username } = req.query; + try { + const user = await User.findOne({ username }); + if (!user) { + return res.status(404).json({ success: false, message: 'Usuario no encontrado' }); + } + // Incrementa las respuestas correctas del usuario + user.correctAnswers += 1; + await user.save(); + return res.status(200).json({ success: true, message: 'Respuesta correcta actualizada con éxito' }); + } catch (error) { + console.error('Error al actualizar la respuesta correcta:', error); + return res.status(500).json({ success: false, message: 'Error al actualizar la respuesta correcta' }); + } +}) + const server = app.listen(port, () => { console.log(`User Service listening at http://localhost:${port}`); });