Skip to content

Commit

Permalink
question-service updated
Browse files Browse the repository at this point in the history
  • Loading branch information
angelalvaigle committed Nov 12, 2024
1 parent 9e5f6e4 commit cee662a
Show file tree
Hide file tree
Showing 12 changed files with 145 additions and 79 deletions.
15 changes: 15 additions & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
58 changes: 58 additions & 0 deletions questionservice/question-controller.js
Original file line number Diff line number Diff line change
@@ -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 });
}
};
6 changes: 3 additions & 3 deletions questionservice/question-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
});

Expand Down
15 changes: 15 additions & 0 deletions questionservice/question-router.js
Original file line number Diff line number Diff line change
@@ -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;
32 changes: 3 additions & 29 deletions questionservice/question-service.js
Original file line number Diff line number Diff line change
@@ -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}`);
Expand Down
4 changes: 2 additions & 2 deletions users/authservice/auth-router.js
Original file line number Diff line number Diff line change
@@ -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();

Expand Down
2 changes: 1 addition & 1 deletion users/authservice/auth-service.js
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
5 changes: 1 addition & 4 deletions users/userservice/user-router.js
Original file line number Diff line number Diff line change
@@ -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();

Expand Down
5 changes: 2 additions & 3 deletions users/userservice/user-service.js
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
76 changes: 44 additions & 32 deletions webapp/src/components/QuestionContainer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down Expand Up @@ -65,43 +66,54 @@ const QuestionContainer = ({
}
}, [showResult]); //, loadNextQuestion]);

// Función para manejar la carga de la imagen
const handleImageLoad = () => {
setIsImageLoaded(true);
};

return (
<Wrapper>
{/* Título de la obra */}
<h3>{`¿Quién creó la obra "${name}"?`}</h3>
{!isImageLoaded && <div>Loading...</div>}
{isImageLoaded && (
/* Título de la obra */
<h3>{`¿Quién creó la obra "${name}"?`}</h3>
)}
{/* Imagen de la obra */}
<div className="image">
<img src={path} alt={name} />
<img src={path} alt={name} onLoad={handleImageLoad} />
</div>
<div>
<h5>Descarta las respuestas incorrectas</h5>
</div>
{/* Renderizar botones con las respuestas */}
<div className="buttons-container">
{shuffledAnswers.map((answer, index) => (
<button
className={`btn ${
selectedAnswer === right
? answer === right && incorrectAnswers.length === 3 // Marca la respuesta correcta cuando se selecciona
? 'correct'
: 'disabled' // Deshabilita las demás cuando la correcta es seleccionada
: incorrectAnswers.includes(answer) // Marca las respuestas incorrectas una a una
? 'incorrect'
: ''
}`}
key={index}
onClick={() => handleAnswerClick(answer)}
disabled={
selectedAnswer !== null ||
incorrectAnswers.includes(answer) ||
!isActive // Deshabilita
}
>
{answer}
</button>
))}
</div>

{isImageLoaded && (
<div>
<h5>Descarta las respuestas incorrectas</h5>
</div>
)}
{isImageLoaded && (
/* Renderizar botones con las respuestas */
<div className="buttons-container">
{shuffledAnswers.map((answer, index) => (
<button
className={`btn ${
selectedAnswer === right
? answer === right && incorrectAnswers.length === 3 // Marca la respuesta correcta cuando se selecciona
? 'correct'
: 'disabled' // Deshabilita las demás cuando la correcta es seleccionada
: incorrectAnswers.includes(answer) // Marca las respuestas incorrectas una a una
? 'incorrect'
: ''
}`}
key={index}
onClick={() => handleAnswerClick(answer)}
disabled={
selectedAnswer !== null ||
incorrectAnswers.includes(answer) ||
!isActive // Deshabilita
}
>
{answer}
</button>
))}
</div>
)}
{/* Mostrar el resultado después de seleccionar */}
{selectedAnswer && (
<div>
Expand Down
4 changes: 1 addition & 3 deletions webapp/src/pages/Play.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -28,8 +28,6 @@ const Play = () => {
fetchQuestions(); // Llamada a la función de carga
}, []);

console.log(questions);

return (
<div>
{loading ? (
Expand Down
2 changes: 0 additions & 2 deletions webapp/src/pages/PlayGame1.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down

0 comments on commit cee662a

Please sign in to comment.