Skip to content

Commit

Permalink
Merge pull request #123 from Arquisoft/carlos
Browse files Browse the repository at this point in the history
Cambiando código del servicio de usuarios al de devolver preguntas
  • Loading branch information
baraganio authored Apr 8, 2024
2 parents 5d8ad9e + 4a536c1 commit a2632df
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 63 deletions.
4 changes: 2 additions & 2 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ app.post('/adduser', async (req, res) => {

app.post('/addgame', async (req, res) => {
try {
const userResponse = await axios.post(userServiceUrl+'/addgame', req.body);
const userResponse = await axios.post(retrieveServiceUrl+'/addgame', req.body);
res.json(userResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
Expand All @@ -60,7 +60,7 @@ app.post('/addgame', async (req, res) => {
app.get('/getgamehistory/:username', async (req, res) => {
try {
const username = req.params.username;
const userResponse = await axios.get(`${userServiceUrl}/getgamehistory/${username}`);
const userResponse = await axios.get(`${retrieveServiceUrl}/getgamehistory/${username}`);
res.json(userResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const mongoose = require('mongoose');
const gameSchema = new mongoose.Schema({
username: { type: String, required: true },
duration: Number,
questions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Question' }],
questions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'QuestionAnswered' }],
date: { type: Date, default: Date.now } ,
percentage: Number,
totalQuestions: Number,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ const questionSchema = new mongoose.Schema({
userAnswer: String
});

const Question = mongoose.model('Question', questionSchema);
const QuestionAnswered = mongoose.model('QuestionAnswered', questionSchema);

module.exports = Question;
module.exports = QuestionAnswered
58 changes: 58 additions & 0 deletions questions/retrieveservice/retrieve-service.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const express = require('express');
const mongoose = require('mongoose');
const Question = require('./questionshistory-model')
const Game = require('./playedGame-model')
const QuestionAnswered = require('./question-model')

const app = express();
const port = 8004;
Expand All @@ -22,6 +24,62 @@ app.get('/getquestionshistory', async (req, res) => {
res.status(200).json(solution);
});

app.post('/addgame', async (req, res) => {
try {
// Obtener los datos del juego desde el cuerpo de la solicitud
const gameData = req.body;

// Convertir las preguntas del juego en ObjectId
const questionIds = await Promise.all(gameData.questions.map(async (question) => {
const existingQuestion = await QuestionAnswered.findOne({
question: question.question,
correctAnswer: question.correctAnswer,
userAnswer: question.userAnswer
});
if (existingQuestion) {
return existingQuestion._id;
} else {
const newQuestion = new QuestionAnswered(question);
await newQuestion.save();
return newQuestion._id;
}
}));

// Reemplazar las preguntas en el juego con sus ObjectId
gameData.questions = questionIds;

// Crear una nueva instancia del modelo de juego con los datos proporcionados
const newGame = new Game(gameData);

// Guardar el nuevo juego en la base de datos
await newGame.save();

// Enviar una respuesta de éxito
res.status(200).json({ message: "Partida guardada exitosamente" });
} catch (error) {
// Manejar errores y enviar una respuesta de error con el mensaje de error
console.error("Error al guardar el juego:", error);
res.status(400).json({ error: error.message });
}
});



app.get('/getgamehistory/:username', async (req, res) => {
try {
const username = req.params.username;
console.log("Se está intentando encontrar el historial del usuario " + username);
// Buscar las partidas asociadas al nombre de usuario proporcionado
const games = await Game.find({ username }).populate('questions');
console.log("Se encontraron los juegos para " + username + ": ", games);
res.json(games);
} catch (error) {
res.status(400).json({
error: error.message
});
}
});

const server = app.listen(port, () => {
console.log(`Creation Service listening at http://localhost:${port}`);
});
Expand Down
58 changes: 0 additions & 58 deletions users/userservice/user-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');
const User = require('./user-model')
const Game = require('./playedGame-model')
const Question = require('./question-model')

const app = express();
const port = 8001;
Expand Down Expand Up @@ -50,62 +48,6 @@ app.post('/adduser', async (req, res) => {
}
});

app.post('/addgame', async (req, res) => {
try {
// Obtener los datos del juego desde el cuerpo de la solicitud
const gameData = req.body;

// Convertir las preguntas del juego en ObjectId
const questionIds = await Promise.all(gameData.questions.map(async (question) => {
const existingQuestion = await Question.findOne({
question: question.question,
correctAnswer: question.correctAnswer,
userAnswer: question.userAnswer
});
if (existingQuestion) {
return existingQuestion._id;
} else {
const newQuestion = new Question(question);
await newQuestion.save();
return newQuestion._id;
}
}));

// Reemplazar las preguntas en el juego con sus ObjectId
gameData.questions = questionIds;

// Crear una nueva instancia del modelo de juego con los datos proporcionados
const newGame = new Game(gameData);

// Guardar el nuevo juego en la base de datos
await newGame.save();

// Enviar una respuesta de éxito
res.status(200).json({ message: "Partida guardada exitosamente" });
} catch (error) {
// Manejar errores y enviar una respuesta de error con el mensaje de error
console.error("Error al guardar el juego:", error);
res.status(400).json({ error: error.message });
}
});



app.get('/getgamehistory/:username', async (req, res) => {
try {
const username = req.params.username;
console.log("Se está intentando encontrar el historial del usuario " + username);
// Buscar las partidas asociadas al nombre de usuario proporcionado
const games = await Game.find({ username }).populate('questions');
console.log("Se encontraron los juegos para " + username + ": ", games);
res.json(games);
} catch (error) {
res.status(400).json({
error: error.message
});
}
});

const server = app.listen(port, () => {
console.log(`User Service listening at http://localhost:${port}`);
});
Expand Down

0 comments on commit a2632df

Please sign in to comment.