Skip to content

Commit

Permalink
arreglar bug dependencias y programdor de preguntas
Browse files Browse the repository at this point in the history
  • Loading branch information
bidof committed Mar 6, 2024
1 parent ba9ee29 commit 36d19e8
Show file tree
Hide file tree
Showing 9 changed files with 94 additions and 10 deletions.
5 changes: 2 additions & 3 deletions api_interfaces/api_questionservice.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,5 @@ const example_data = {question: 'pregunta ejemplo', respuesta: [
{answer: 'respuesta incorrecta1', correct: false},
{answer: 'respuesta incorrecta2', correct: false},
{answer: 'respuesta incorrecta3', correct: false}],
questionCategory: 'geografia',
questionType:'capital'
};
questionCategory: 'geografia'
};
6 changes: 5 additions & 1 deletion gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ app.get('/getquestion', async(req,res)=> {
res.json(response.data);

} catch(error) {
res.status(error.response.status).json({ error: error.response.data.error });
if (error.response) {
res.status(error.response.status).json({ error: error.response.data.error });
} else {
res.status(500).json({ error: 'An unexpected error occurred' });
}
}
});

Expand Down
20 changes: 20 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"dotenv": "^16.4.5",
"mysql": "^2.18.1",
"mysql2": "^3.9.2",
"node-cron": "^3.0.3",
"react-bootstrap": "^2.10.1"
}
}
44 changes: 44 additions & 0 deletions questionservice/DataBaseManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,50 @@ async connect() {
await this.disconnect();
}
}
async getGameQuestions() {
try {
await this.connect();

// Obtén una pregunta aleatoria
const [question] = await this.connection.execute(
'SELECT * FROM Pregunta ORDER BY RAND() LIMIT 1'
);

const questionId = question[0].id_pregunta;

// Obtén la respuesta correcta para esa pregunta
const correctAnswer = question[0].respuesta_correcta;

// Obtén los distractores para esa pregunta
const [distractors] = await this.connection.execute(
'SELECT distractor FROM Distractor WHERE id_pregunta = ?',
[questionId]
);

// Obtén la categoría de la pregunta
const [category] = await this.connection.execute(
'SELECT nombre_categoria FROM Categoria WHERE id_categoria = ?',
[question[0].id_categoria]
);

return {
question: question[0].pregunta,
respuesta: [
{ answer: correctAnswer, correct: true },
...distractors.map(distractor => ({ answer: distractor.distractor, correct: false }))
],
questionCategory: category[0].nombre_categoria
};

} catch (error) {
console.error('Error getting game questions:', error.message);
throw error;
} finally {
// Desconectar de la base de datos
await this.disconnect();
}
}

}


Expand Down
4 changes: 3 additions & 1 deletion questionservice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.4",
"mysql2": "^3.9.2"
"mysql2": "^3.9.2",
"node-cron": "^3.0.0"

},
"devDependencies": {
"jest": "^29.7.0",
Expand Down
14 changes: 14 additions & 0 deletions questionservice/question-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,23 @@ const getQuestionTemplate = require('./questionTemplates');
//agregar el servicio de guardarlas en bd
const DatabaseManager = require('./DataBaseManager');
const questionService = new DatabaseManager();
const Scheduler = require('./scheduler');
const scheduler = new Scheduler(); // Crea una nueva instancia de la clase

scheduler.start();//iniciar el servicio de crear las preguntas
app.use(express.json());

app.post('/getquestion', async (req, res) => {
try{

const questionAndAnswer = await questionService.getGameQuestions(); // Obtenemos el json de pregunta y sus respuestas
//const questionAndAnswer = await getQuestionTemplate(); // Obtenemos el json de pregunta y sus respuestas

res.json(questionAndAnswer); //Devolvemos a la gateway el json
}catch(error){
console.log("Error getting question from BD: " + error);
}
/*
try {
const questionAndAnswer = await getQuestionTemplate(); // Obtenemos el json de pregunta y sus respuestas
Expand All @@ -33,6 +46,7 @@ app.post('/getquestion', async (req, res) => {
console.error("Error generating question:", error);
res.status(500).json({ error: "Internal server error when generating the question" });
}
*/
});


Expand Down
4 changes: 1 addition & 3 deletions questionservice/questionTemplates.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,14 @@ const templates = [
const correctAnswer = { answer: country.capital, correct: true };
const fakeAnswers = fakeCities.map(city => ({ answer: city, correct: false }));
const answers = [correctAnswer, ...fakeAnswers];
const type = "capital";//representa porque estas preguntando
const categoria="Geografía";
// Mezclamos las respuestas para que la posición de la correcta sea aleatoria
const shuffledAnswers = shuffleArray(answers);

return {
question: `¿Cuál es la capital de ${country.name}?`,
answers: shuffledAnswers,
questionCategory: categoria,
questionType:type
questionCategory: categoria
};
},
// Aquí podemos añadir más templates
Expand Down
6 changes: 4 additions & 2 deletions questionservice/scheduler.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//clase encargada de generar preguntas cada hora , se tiene que isntaciar para poder usarsel y llamar a start
//llamado desde el question-service.js
const cron = require('node-cron');
const DataBaseManager = require('./DataBaseManager'); // Asegúrate de que la ruta sea correcta
const getQuestionTemplate = require('./questionTemplates');
Expand All @@ -8,12 +9,13 @@ class Scheduler {
this.dbManager = new DataBaseManager();
}


start() {
cron.schedule('0 * * * *', async () => {
cron.schedule('*/30 * * * *', async () => {
let success = false;
while (!success) {
try {
const templates = await getQuestionTemplate(); // Obtenemos el json de pregunta y sus respuestas
const templates = await getQuestionTemplate(); // Obtenemos el json de pregunta y sus respuestas
await this.dbManager.addQuestion(templates);
success = true;
} catch (error) {
Expand Down

0 comments on commit 36d19e8

Please sign in to comment.