Skip to content

Commit

Permalink
Merge branch 'master' into development-angela
Browse files Browse the repository at this point in the history
  • Loading branch information
angeeroza committed Apr 15, 2024
2 parents 597f535 + a767826 commit cac58dd
Show file tree
Hide file tree
Showing 36 changed files with 661 additions and 151 deletions.
84 changes: 82 additions & 2 deletions gamehistoryservice/gamehistory.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ app.get("/gamehistory", async (req, res) => {
totalQuestionsAnswered: gamehistory.totalQuestionsAnswered,
totalRightQuestions: gamehistory.totalRightQuestions,
totalIncorrectQuestions: gamehistory.totalIncorrectQuestions,
ratio: gamehistory.ratio + " %",
totalTime: gamehistory.totalTime + " s"
ratio: gamehistory.ratio + "%",
totalTime: gamehistory.totalTime + "s"
};
res.json(response);
} else {
Expand All @@ -65,6 +65,29 @@ app.get("/gamehistory", async (req, res) => {
}
});

app.get("/endgamestats", async (req, res) => {
try {
const userId = req.query.username;
const gameStats = await getEndGameStats(userId);

// Formatea la respuesta JSON
const response = {
totalRightQuestions: gameStats.totalRightQuestions || 0,
totalIncorrectQuestions: gameStats.totalIncorrectQuestions || 0,
ratio: (gameStats.ratio || 0) + "%",
totalTime: (gameStats.totalTime || 0) + "s",
endgameImageWithRatio: gameStats.ratio
};

// Envía la respuesta JSON
res.json(response);

} catch (error) {
res.status(400).json({ error: "Error al obtener las estadísticas de la partida: " + error.message });
}
});


async function saveGameHistory(userId) {
try {

Expand Down Expand Up @@ -121,6 +144,63 @@ async function saveGameHistory(userId) {
}
}

app.get("/topUsers", async (req, res) => {
try {
const topUsers = await GameHistory.find()
.sort({ ratio: -1 }) // Ordena porcentaje de aciertos de mayor a menor
const response = {
primero: topUsers[0] ? topUsers[0].userId + " - " + topUsers[0].ratio + "%" : "",
segundo: topUsers[1] ? topUsers[1].userId + " - " + topUsers[1].ratio + "%": "",
tercero: topUsers[2] ? topUsers[2].userId + " - " + topUsers[2].ratio + "%": ""
};
res.json(response);
} catch (error) {
res.status(400).json({ error: "Error al obtener el ranking de usuarios: " + error.message });
}
});

async function getEndGameStats(userId) {
try {
// Busca las partidas del usuario y ordena por fecha descendente para obtener la última partida
const games = await mongoose.connection.collection('games').aggregate([
{
$match: { userId: userId }
},
{
$sort: { createdAt: -1 }
},
{
$lookup: {
from: 'questions',
localField: 'questions',
foreignField: '_id',
as: 'questionsData'
}
},
]).toArray();

// Calcula las estadísticas de la última partida
const lastGame = games[0];
const totalQuestionsAnswered = lastGame.questionsData.length;
const totalRightQuestions = lastGame.questionsData.filter(question => question.correct).length;
const totalIncorrectQuestions = totalQuestionsAnswered - totalRightQuestions;
const totalTime = lastGame.questionsData.reduce((acc, curr) => acc + (curr.time ?? 0), 0);
const ratio = totalQuestionsAnswered === 0 ? 0 : parseInt((totalRightQuestions / totalQuestionsAnswered) * 100);

// Devuelve las estadísticas
return {
totalRightQuestions,
totalIncorrectQuestions,
ratio,
totalTime
};

} catch (error) {
console.error('Error al obtener las estadísticas de la partida:', error);
throw error;
}
}


const server = app.listen(port, () => {
console.log(`Stats Service listening at http://localhost:${port}`);
Expand Down
55 changes: 9 additions & 46 deletions gamehistoryservice/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions gamehistoryservice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
},
"homepage": "https://github.com/arquisoft/wiq_es2c#readme",
"dependencies": {
"axios": "^0.21.1",
"bcrypt": "^5.1.1",
"body-parser": "^1.20.2",
"express": "^4.18.2",
"mongoose": "^8.0.4",
"axios": "^0.21.1"
"express": "^4.19.2",
"mongoose": "^8.0.4"
},
"devDependencies": {
"jest": "^29.7.0",
Expand Down
40 changes: 40 additions & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ app.post('/saveGameHistory', async (req, res) => {
}
});

app.post('/configureGame', async (req, res) => {
try {
const response = await axios.post(generatorUrl+'/configureGame', req.body);
res.json(response.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
}
});

app.get('/gamehistory', async (req, res) => {
try {
const URL = gamehistoryUrl + '/gamehistory?username=' + req.query.username;
Expand Down Expand Up @@ -123,6 +132,37 @@ app.get('/getAllQuestions', async (req, res) => {
}
});

app.get('/topUsers', async (req, res) => {
try {
const response = await axios.get(gamehistoryUrl+'/topUsers', req.body);
res.json(response.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
}
});

app.get('/endgamestats', async (req, res) => {
try {
const URL = gamehistoryUrl + '/endgamestats?username=' + req.query.username;
const response = await axios.get(URL);
res.json(response.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
}
});

app.get('/restartGame', async (req, res) => {
try {
const URL = generatorUrl + '/restartGame';
const response = await axios.get(URL);
res.json(response.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });

}
});


// Read the OpenAPI YAML file synchronously
// Hubo que cambiar el path porque los test e2e ahora sólo se ejecutan desde webapp
openapiPath='../gatewayservice/openapi.yaml'
Expand Down
13 changes: 8 additions & 5 deletions questiongenerator/game-model.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
const mongoose = require('mongoose');

const gameSchema = new mongoose.Schema({
userId:{
userId: {
type: String,
ref: 'User',
required: true,
},
questions: [
{
type: mongoose.Schema.Types.ObjectId,
ref:'Question'
ref: 'Question'
}
]

],
createdAt: {
type: Date,
default: Date.now
}
});

const Game = mongoose.model('Game', gameSchema);

module.exports = Game
module.exports = Game;
26 changes: 25 additions & 1 deletion questiongenerator/question.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ var numberOfQuestions = 0;
// Número aleatorio que decide la consulta y la pregunta que se mostrarán
var randomNumber;

var maxQuestions = 5;

const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/questiondb';
mongoose.connect(mongoUri);

Expand All @@ -54,7 +56,7 @@ app.get('/generateQuestion', async (req, res) => {
const user = req.query.user;
await generarPregunta();
numberOfQuestions++;
if(numberOfQuestions>=5){
if(numberOfQuestions>=maxQuestions){
numberOfQuestions = 0;
}
var id = await saveData();
Expand All @@ -76,10 +78,22 @@ app.get('/generateQuestion', async (req, res) => {
}
});

app.post('/configureGame', async (req, res) => {
try {
maxQuestions = req.body.valueQuestion;
res.status(200).json(maxQuestions);
} catch (error) {
console.log("Error: " + error)
res.status(400).json({ error: error.message });
}
});

var server = app.listen(port, () => {
console.log(`Questions Generation Service listening at http://localhost:${port}`);
});



async function generarPregunta() {
randomNumber = Math.floor(Math.random() * 2);
try {
Expand Down Expand Up @@ -235,5 +249,15 @@ app.get('/updateQuestion', async (req, res) => {
}
});

app.get('/restartGame', async (req,res) => {
try{
numberOfQuestions = 0;
res.status(200).json({ message: "Número de preguntas actualizado", numberOfQuestions });
}catch (error){
res.status(400).json({ error: error.message });
}

});


module.exports = server
19 changes: 19 additions & 0 deletions users/userservice/user-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,29 @@ function validateRequiredFields(req, requiredFields) {
}
}

function validateRequiredFieldsContent(username,email,password){
if(username.trim().length === 0 || email.trim().length === 0 || password.trim().length === 0 ){
throw new Error(`Los campos no pueden estar vacíos`);
}else{

const regex = /@gmail\.com$/;
if(!regex.test(email)){
throw new Error(`El email debe acabar con @gmail.com`);
}else{

if(password.trim().length < 8){
throw new Error(`La contraseña debe tener al menos 8 caracteres`);
}

}
}
}

app.post('/adduser', async (req, res) => {
try {
// Check if required fields are present in the request body
validateRequiredFields(req, ['username', 'email','password']);
validateRequiredFieldsContent(req.body.username,req.body.email,req.body.password);
const { username,email, password } = req.body;
const user_Username = await User.findOne({ username });
const user_Email = await User.findOne({ email });
Expand Down
Loading

0 comments on commit cac58dd

Please sign in to comment.