Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jota #79

Merged
merged 3 commits into from
Mar 27, 2024
Merged

Jota #79

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 9 additions & 15 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -52,20 +53,13 @@ app.get('/pregunta', async (req, res) => {
});

app.get('/updateCorrectAnswers', async (req, res) => {
console.log("prueba")
const { username } = req.body;
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' });
console.log(req.query)
const { username } = req.query;
try{
const updateStatsResponse = await axios.get(userServiceUrl+ `/updateCorrectAnswers?username=${username}`)
res.json(updateStatsResponse.data);
}catch(error){
res.status(error.response.status).json({error: error.response.data.error});
}
});

Expand Down
File renamed without changes.
File renamed without changes.
20 changes: 19 additions & 1 deletion userservice/userservice/user-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}`);
});
Expand Down
14 changes: 11 additions & 3 deletions webapp/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { useNavigate } from 'react-router-dom';

function App() {
const [isLogged, setIsLogged] = useState(false);
const [username, setUsername] = useState("");

useEffect(() => {
const storedIsLogged = localStorage.getItem('isLogged');
Expand All @@ -21,6 +22,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 }) {
const navigate = useNavigate();
Expand All @@ -39,11 +47,11 @@ function App() {
<Routes>
<Route path="/" element={<Home isLogged={isLogged}/>}></Route>
<Route path="/game"
element={<PrivateRoute element={<Juego isLogged={isLogged} />} />}
element={<PrivateRoute element={<Juego isLogged={isLogged} username={username} />} />}
/>
<Route path="/login" element={<Login isLogged={isLogged} setIsLogged={setIsLogged} />} />
<Route path="/login" element={<Login isLogged={isLogged} setIsLogged={setIsLogged} username={username} setUsername={setUsername}/>} />
<Route path="*" element={<NotFound />} />
<Route path="/register" element={<AddUser isLogged={isLogged}/>}/>
<Route path="/register" element={<AddUser isLogged={isLogged} username={username} />}/>

<Route
path="/stats"
Expand Down
8 changes: 3 additions & 5 deletions webapp/src/components/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import React, { useState } from 'react';
import axios from 'axios';
import { Container, Typography, TextField, Button, Snackbar } from '@mui/material';

const Login = ({isLogged, setIsLogged}) => {
const [username, setUsername] = useState('');
const Login = ({isLogged, setIsLogged, username, setUsername}) => {
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [createdAt, setCreatedAt] = useState('');
Expand All @@ -21,9 +20,8 @@ const Login = ({isLogged, setIsLogged}) => {
setCreatedAt(datos.createdAt);
setIsLogged(true);
localStorage.setItem('isLogged', JSON.stringify(true));
//Guardamos nombre de usuario
localStorage.setItem('username', username);

setUsername(datos.username)
localStorage.setItem('username', JSON.stringify(datos.username))
setOpenSnackbar(true);
} catch (error) {
setError(error.response.data.error);
Expand Down
49 changes: 27 additions & 22 deletions webapp/src/components/Pages/Juego.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import { Container } from '@mui/material';
import Temporizador from '../Temporizador';
import { jwtDecode } from 'jwt-decode';


const Juego = ({isLogged}) => {
const Juego = ({isLogged, username}) => {
//La pregunta (string)
const [pregunta, setPregunta] = useState("")
//La Respuesta correcta (string)
Expand All @@ -21,33 +20,30 @@ const Juego = ({isLogged}) => {
//Para saber si el temporizador se ha parado al haber respondido una respuesta
const [pausarTemporizador, setPausarTemporizador] = useState(false)

//Variables para la obtencion y modificacion de estadisticas del usuario
const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';
const [username, setUsername] = useState('');
const User = require('../../models/user-model');
const [error, setError] = useState('');
const [password, setPassword] = useState('');

//Variables para la obtencion y modificacion de estadisticas del usuario
const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';
const [error, setError] = useState('');
const [password, setPassword] = useState('');

const updateCorrectAnswers = async () => {
try {
const username = localStorage.getItem('username');
const response = await axios.get(`${apiEndpoint}/updateCorrectAnswers?username=${username}`);
console.log('Respuesta correcta actualizada con éxito:', response.data);
// Realizar otras acciones según sea necesario
} catch (error) {
console.error('Error al actualizar la respuesta correcta:', error);
// Manejar el error de acuerdo a tus necesidades
}
};

const updateCorrectAnswers = async () => {
try {
const response = await axios.get(`${apiEndpoint}/updateCorrectAnswers?username=${username}`);
console.log('Respuesta correcta actualizada con éxito:', response.data);
// Realizar otras acciones según sea necesario
} catch (error) {
console.error('Error al actualizar la respuesta correcta:', error);
// Manejar el error de acuerdo a tus necesidades
}
};
////


//Operacion asíncrona para cargar pregunta y respuestas en las variables desde el json
//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)
Expand Down Expand Up @@ -76,11 +72,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)
Expand Down
Loading