From cee662a98efeecbce5aa5aea76f6fa1f013aadb1 Mon Sep 17 00:00:00 2001 From: angelalvaigle Date: Wed, 13 Nov 2024 00:00:30 +0100 Subject: [PATCH] question-service updated --- gatewayservice/gateway-service.js | 15 ++++ questionservice/question-controller.js | 58 ++++++++++++++++ questionservice/question-model.js | 6 +- questionservice/question-router.js | 15 ++++ questionservice/question-service.js | 32 +-------- users/authservice/auth-router.js | 4 +- users/authservice/auth-service.js | 2 +- users/userservice/user-router.js | 5 +- users/userservice/user-service.js | 5 +- webapp/src/components/QuestionContainer.jsx | 76 ++++++++++++--------- webapp/src/pages/Play.jsx | 4 +- webapp/src/pages/PlayGame1.jsx | 2 - 12 files changed, 145 insertions(+), 79 deletions(-) create mode 100644 questionservice/question-controller.js create mode 100644 questionservice/question-router.js diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index 9c41d96..ca7b89f 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -96,6 +96,21 @@ app.get('/questions', async (req, res) => { } }); +app.get('/game-questions', async (req, res) => { + try { + // Forward the get question request to the question asking service + const getQuestionResponse = await axios.get( + questionServiceUrl + '/game-questions', + req.body + ); + res.json(getQuestionResponse.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)) { diff --git a/questionservice/question-controller.js b/questionservice/question-controller.js new file mode 100644 index 0000000..cc2c27b --- /dev/null +++ b/questionservice/question-controller.js @@ -0,0 +1,58 @@ +const Question = require('./question-model'); + +// Function to validate required fields in the request body +function validateRequiredFields(req, requiredFields) { + for (const field of requiredFields) { + if (!(field in req.body)) { + throw new Error(`Missing required field: ${field}`); + } + } +} + +exports.addQuestionsController = async (req, res) => { + try { + // Check if required fields are present in the request body + validateRequiredFields(req, [ + 'type', + 'name', + 'path', + 'right', + 'wrong1', + 'wrong2', + 'wrong3', + ]); + + const newQuestion = new Question({ + type: req.body.type, + name: req.body.name, + path: req.body.path, + right: req.body.right, + wrong1: req.body.wrong1, + wrong2: req.body.wrong2, + wrong3: req.body.wrong3, + }); + + await newQuestion.save(); + res.json(newQuestion); + } catch (error) { + res.status(400).json({ error: error.message }); + } +}; + +exports.getQuestionsController = async (req, res) => { + try { + const questions = await Question.find(); // Fetch all questions + res.json(questions); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; + +exports.getGameQuestionsController = async (req, res) => { + try { + const questions = await Question.aggregate([{ $sample: { size: 5 } }]); + res.json(questions); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; diff --git a/questionservice/question-model.js b/questionservice/question-model.js index ce4047b..a243da7 100644 --- a/questionservice/question-model.js +++ b/questionservice/question-model.js @@ -19,15 +19,15 @@ const questionSchema = new mongoose.Schema({ }, wrong1: { type: String, - // required: true, + required: true, }, wrong2: { type: String, - // required: true, + required: true, }, wrong3: { type: String, - // required: true, + required: true, }, }); diff --git a/questionservice/question-router.js b/questionservice/question-router.js new file mode 100644 index 0000000..72677a0 --- /dev/null +++ b/questionservice/question-router.js @@ -0,0 +1,15 @@ +const express = require('express'); +const { + addQuestionsController, + getQuestionsController, + getGameQuestionsController, +} = require('./question-controller'); + +const questionRouter = express.Router(); + +// Define la ruta para el login y asocia el controlador +questionRouter.post('/addquestion', addQuestionsController); +questionRouter.get('/questions', getQuestionsController); +questionRouter.get('/game-questions', getGameQuestionsController); + +module.exports = questionRouter; diff --git a/questionservice/question-service.js b/questionservice/question-service.js index f8d6053..f121cfa 100644 --- a/questionservice/question-service.js +++ b/questionservice/question-service.js @@ -1,46 +1,20 @@ // question-service.js const express = require('express'); const mongoose = require('mongoose'); -const bodyParser = require('body-parser'); -const Question = require('./question-model'); +const questionRouter = require('./question-router'); const app = express(); const port = 8003; // Middleware to parse JSON in request body -app.use(bodyParser.json()); +app.use(express.json()); // Connect to MongoDB const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/questiondb'; mongoose.connect(mongoUri); -app.post('/addquestion', async (req, res) => { - try { - const newQuestion = new Question({ - type: req.body.type, - name: req.body.name, - path: req.body.path, - right: req.body.right, - wrong1: req.body.wrong1, - wrong2: req.body.wrong2, - wrong3: req.body.wrong3, - }); - await newQuestion.save(); - res.json(newQuestion); - } catch (error) { - res.status(400).json({ error: error.message }); - } -}); - -app.get('/questions', async (req, res) => { - try { - const questions = await Question.aggregate([{ $sample: { size: 5 } }]); - res.json(questions); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); +app.use('/', questionRouter); const server = app.listen(port, () => { console.log(`Question Service listening at http://localhost:${port}`); diff --git a/users/authservice/auth-router.js b/users/authservice/auth-router.js index 5891efb..bb363b4 100644 --- a/users/authservice/auth-router.js +++ b/users/authservice/auth-router.js @@ -1,6 +1,6 @@ -// authRouter.js +// auth-router.js const express = require('express'); -const { loginController } = require('./auth-controller.js'); +const { loginController } = require('./auth-controller'); const authRouter = express.Router(); diff --git a/users/authservice/auth-service.js b/users/authservice/auth-service.js index 20e4f89..772f251 100644 --- a/users/authservice/auth-service.js +++ b/users/authservice/auth-service.js @@ -1,6 +1,6 @@ const express = require('express'); const mongoose = require('mongoose'); -const authRouter = require('./auth-router.js'); +const authRouter = require('./auth-router'); const app = express(); const port = 8002; diff --git a/users/userservice/user-router.js b/users/userservice/user-router.js index 9a7cb31..d987487 100644 --- a/users/userservice/user-router.js +++ b/users/userservice/user-router.js @@ -1,9 +1,6 @@ // userRouter.js const express = require('express'); -const { - addUserController, - getUsersController, -} = require('./user-controller.js'); +const { addUserController, getUsersController } = require('./user-controller'); const userRouter = express.Router(); diff --git a/users/userservice/user-service.js b/users/userservice/user-service.js index 9c39959..5f71749 100644 --- a/users/userservice/user-service.js +++ b/users/userservice/user-service.js @@ -1,14 +1,13 @@ // user-service.js const express = require('express'); const mongoose = require('mongoose'); -const bodyParser = require('body-parser'); -const userRouter = require('./user-router.js'); +const userRouter = require('./user-router'); const app = express(); const port = 8001; // Middleware to parse JSON in request body -app.use(bodyParser.json()); +app.use(express.json()); // Connect to MongoDB const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb'; diff --git a/webapp/src/components/QuestionContainer.jsx b/webapp/src/components/QuestionContainer.jsx index cf8a855..cb3aabb 100644 --- a/webapp/src/components/QuestionContainer.jsx +++ b/webapp/src/components/QuestionContainer.jsx @@ -15,6 +15,7 @@ const QuestionContainer = ({ const [selectedAnswer, setSelectedAnswer] = useState(null); const [incorrectAnswers, setIncorrectAnswers] = useState([]); const [showResult, setShowResult] = useState(false); + const [isImageLoaded, setIsImageLoaded] = useState(false); // Efecto para reiniciar los estados cuando se carga una nueva pregunta useEffect(() => { @@ -65,43 +66,54 @@ const QuestionContainer = ({ } }, [showResult]); //, loadNextQuestion]); + // Función para manejar la carga de la imagen + const handleImageLoad = () => { + setIsImageLoaded(true); + }; + return ( - {/* Título de la obra */} -

{`¿Quién creó la obra "${name}"?`}

+ {!isImageLoaded &&
Loading...
} + {isImageLoaded && ( + /* Título de la obra */ +

{`¿Quién creó la obra "${name}"?`}

+ )} {/* Imagen de la obra */}
- {name} + {name}
-
-
Descarta las respuestas incorrectas
-
- {/* Renderizar botones con las respuestas */} -
- {shuffledAnswers.map((answer, index) => ( - - ))} -
- + {isImageLoaded && ( +
+
Descarta las respuestas incorrectas
+
+ )} + {isImageLoaded && ( + /* Renderizar botones con las respuestas */ +
+ {shuffledAnswers.map((answer, index) => ( + + ))} +
+ )} {/* Mostrar el resultado después de seleccionar */} {selectedAnswer && (
diff --git a/webapp/src/pages/Play.jsx b/webapp/src/pages/Play.jsx index 7f844b5..74467ac 100644 --- a/webapp/src/pages/Play.jsx +++ b/webapp/src/pages/Play.jsx @@ -16,7 +16,7 @@ const Play = () => { // Función asíncrona para obtener los documentos const fetchQuestions = async () => { try { - const response = await axios.get(`${apiEndpoint}/questions`); + const response = await axios.get(`${apiEndpoint}/game-questions`); setQuestions(response.data); // Actualizamos el estado con los datos } catch (error) { console.error('Error al obtener las preguntas:', error); @@ -28,8 +28,6 @@ const Play = () => { fetchQuestions(); // Llamada a la función de carga }, []); - console.log(questions); - return (
{loading ? ( diff --git a/webapp/src/pages/PlayGame1.jsx b/webapp/src/pages/PlayGame1.jsx index d02be12..b45d35a 100644 --- a/webapp/src/pages/PlayGame1.jsx +++ b/webapp/src/pages/PlayGame1.jsx @@ -17,8 +17,6 @@ const PlayGame1 = ({ questions }) => { const [isActive, setIsActive] = useState(true); const [gameOver, setGameOver] = useState(false); - console.log(questions); - // Desestructuramos la pregunta const { name, path, right, wrong1, wrong2, wrong3 } = questions[questionIndex];