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

Añadido funcionaliad de obtener historial #22

Merged
merged 3 commits into from
Mar 26, 2024
Merged
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
14 changes: 14 additions & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ app.get('/getquestions', async(req,res)=> {
}
});

//Guardar el historial
app.post('/savehistory', async (req, res) => {
try{
const historyResponse = await axios.post(historyServiceUrl+'/savehistory', req.body);
Expand All @@ -74,6 +75,19 @@ app.post('/savehistory', async (req, res) => {
}
});

//Obtener el historial
app.get('/gethistory', async (req, res) => {
try{
const historyResponse = await axios.get(historyServiceUrl+'/gethistory', {
params: { username: req.query.username }
});
res.json(historyResponse.data);
}catch(error){
res.status(error.response.status).json({ error: error.response.data.error });
}
});


// Read the OpenAPI YAML file synchronously
openapiPath='./openapi.yaml'
if (fs.existsSync(openapiPath)) {
Expand Down
34 changes: 33 additions & 1 deletion users/historyservice/history-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ mongoose.connect(mongoUri);

app.post('/savehistory', async (req, res) => {
try {
let username = req.body.username;//necesitamos el username
let username = req.body.username; //necesitamos el username

//Extraer los datos de la solicitud
const { NumPreguntasJugadas, NumAcertadas } = req.body;
Expand Down Expand Up @@ -53,6 +53,38 @@ app.post('/savehistory', async (req, res) => {
}
});

app.get('/gethistory', async (req, res) => {
try {

let username = req.query.username;

console.log(username);
// Buscar el historial en la base de datos basado en el nombre de usuario
let historyEntry = await History.findOne({ username: username });

if (historyEntry === null) {

// Si no se encuentra ningún historial para el usuario, crear un nuevo historial con valores igualados a 0
historyEntry = new History({
username: username,
NumJugadas: 0,
NumPreguntasJugadas: 0,
NumAcertadas: 0,
NumFalladas: 0
})

// Guardar el nuevo historial en la base de datos
await historyEntry.save();

}

res.json(historyEntry);

} catch (error) {
res.status(500).json({ error: 'Error al obtener el historial' });
}
});

const server = app.listen(port, () => {
console.log(`History Service listening at http://localhost:${port}`);
});
Expand Down
53 changes: 34 additions & 19 deletions webapp/src/components/pages/Historial.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,53 @@
import React, { useContext, useEffect } from 'react';
import React, {useCallback, useContext, useEffect, useState} from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../../AuthContext';
import '../../App.css';
import './Historial.css';

export default function Historial() {
const navigate = useNavigate();
const { isLoggedIn } = useContext(AuthContext);
const { isLoggedIn, username } = useContext(AuthContext);
const [historialData, setHistorialData] = useState(false);

const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

const fetchHistorialData = useCallback(async () => {
try {
let response = await axios.get(`${apiEndpoint}/gethistory`, {
params: { username: username }
});

console.log(response.data);

setHistorialData(response.data);

} catch (error) {
console.error('Error al obtener el historial:', error);
}
}, [apiEndpoint, username]);


useEffect(() => {
if (!isLoggedIn) {
navigate('/login');
} else {
fetchHistorialData();
}
}, [isLoggedIn, navigate]);

// Datos de ejemplo
const example_data = {
username: 'nombre',
NumJugadas: '20',
NumPreguntasJugadas: '100',
NumAcertadas: '80',
NumFalladas: '20',
};
}, [isLoggedIn, navigate, fetchHistorialData]);

return (
<div className="historial-container">
<h1 className='services'>HISTORIAL</h1>
<div className="user-info">
<h2>{example_data.username}</h2>
<p>Número de Partidas: {example_data.NumJugadas}</p>
<p>Número de Preguntas Jugadas: {example_data.NumPreguntasJugadas}</p>
<p>Número de acertadas: {example_data.NumAcertadas}</p>
<p>Número de falladas: {example_data.NumFalladas}</p>
</div>
{historialData && (
<div className="user-info">
<h2>Nombre de usuario: {historialData.username}</h2>
<p>Número de Partidas: {historialData.NumJugadas}</p>
<p>Número de Preguntas Jugadas: {historialData.NumPreguntasJugadas}</p>
<p>Número de acertadas: {historialData.NumAcertadas}</p>
<p>Número de falladas: {historialData.NumFalladas}</p>
</div>
)}
</div>
);
}
2 changes: 1 addition & 1 deletion webapp/src/components/pages/Jugar.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function Jugar() {
} else {
getQuestions();
}
}, [isLoggedIn, navigate]); // Asegúrate de incluir apiEndpoint en las dependencias si su valor puede cambiar.
}, [isLoggedIn, navigate]);


const handleNextQuestion = useCallback((timeExpired = false) => {
Expand Down