From 4a536c152767cfb34e10f27864267d7c231e50b6 Mon Sep 17 00:00:00 2001 From: baraganio Date: Mon, 8 Apr 2024 17:32:43 +0200 Subject: [PATCH] =?UTF-8?q?Cambiando=20c=C3=B3digo=20del=20servicio=20de?= =?UTF-8?q?=20usuarios=20al=20de=20devolver=20preguntas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gatewayservice/gateway-service.js | 4 +- .../retrieveservice}/playedGame-model.js | 2 +- .../retrieveservice}/question-model.js | 4 +- questions/retrieveservice/retrieve-service.js | 58 +++++++++++++++++++ users/userservice/user-service.js | 58 ------------------- 5 files changed, 63 insertions(+), 63 deletions(-) rename {users/userservice => questions/retrieveservice}/playedGame-model.js (95%) rename {users/userservice => questions/retrieveservice}/question-model.js (59%) diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index 82e9f886..23c20b64 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -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 }); @@ -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 }); diff --git a/users/userservice/playedGame-model.js b/questions/retrieveservice/playedGame-model.js similarity index 95% rename from users/userservice/playedGame-model.js rename to questions/retrieveservice/playedGame-model.js index ef3f07cd..43b1bb13 100644 --- a/users/userservice/playedGame-model.js +++ b/questions/retrieveservice/playedGame-model.js @@ -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, diff --git a/users/userservice/question-model.js b/questions/retrieveservice/question-model.js similarity index 59% rename from users/userservice/question-model.js rename to questions/retrieveservice/question-model.js index 80b3edcd..94fd1a3b 100644 --- a/users/userservice/question-model.js +++ b/questions/retrieveservice/question-model.js @@ -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 diff --git a/questions/retrieveservice/retrieve-service.js b/questions/retrieveservice/retrieve-service.js index 0d65c42a..c0b233f4 100644 --- a/questions/retrieveservice/retrieve-service.js +++ b/questions/retrieveservice/retrieve-service.js @@ -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; @@ -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}`); }); diff --git a/users/userservice/user-service.js b/users/userservice/user-service.js index 9f083dba..2cbe99ea 100644 --- a/users/userservice/user-service.js +++ b/users/userservice/user-service.js @@ -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; @@ -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}`); });