generated from Arquisoft/wiq_0
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquestions-service.js
113 lines (89 loc) · 3.19 KB
/
questions-service.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// questions-service.js
const express = require('express');
const bodyParser = require('body-parser');
const QuestionGenerator = require('./questionGenerator.js');
const QuestionsRepository = require('./questions-repo.js');
const app = express();
app.disable('x-powered-by');
const port = 8003;
// Middleware to parse JSON in request body
app.use(bodyParser.json());
const questionRepo = new QuestionsRepository();
//to respond to the /getQuestion request
app.get('/getQuestion', async (req, res) => {
try {
//category of the game chosen
const category = req.query.category;
//if the category is all, it will choose a random question from all the categories
const question = await getRandomQuestionByCategory(category);
if (question) {
var tittle = question.tittle;
var correctAnswer = question.answers[question.correctAnswer];
var answerSet = question.answers;
// Delete the question so as not to have repeated questions.
questionRepo.delete(question);
// await Question.deleteOne({ _id: question._id });
res.json({ question: tittle, correctAnswerLabel: correctAnswer, answerLabelSet: answerSet });
}
} catch (error) {
res.status(500).json({ error: 'Internal Server Error inside service' });
}
});
app.get('/generateQuestions', async (req, res) => {
const generator = new QuestionGenerator();
await generator.loadTemplates();
await generator.generate10Questions();
res.status(200).json({ msg: "Questions generated successfully" });
})
app.get('/getAllQuestions', async (req, res) => {
try {
console.log("getall in qs");
const questions = await questionRepo.getAll();
//const questions = await Question.findAll();
res.json(questions);
} catch (error) {
res.status(500).json({ error: 'Internal Server Error trying to get questions' });
}
});
async function getRandomQuestionByCategory(category) {
try {
let query = {}; // Inicializar consulta vacía por defecto
// Verificar si la categoría es "todo" o algo diferente
if (category !== 'todo') {
// Si no es "todo", construir la consulta para la categoría especificada
query = { category: category };
} else {
query = {};
}
const randomQuestion = questionRepo.getQuestion(query);
/*
const randomQuestion = await Question.aggregate([
{ $match: query }, // Filtrar por categoría si no es "todo"
{ $sample: { size: 1 } } // Obtener una muestra aleatoria
]);
*/
if (randomQuestion) {
return randomQuestion; // Devuelve la pregunta aleatoria encontrada
}
else {
if (category === 'todo') {
console.log('No se encontraron preguntas en la base de datos.');
} else {
console.log(`No se encontraron preguntas en la categoría "${category}".`);
}
return null;
}
} catch (error) {
console.error('Error al buscar la pregunta aleatoria:', error);
return null;
}
}
const server = app.listen(port, () => {
console.log(`Question Generator Service listening at http://localhost:${port}`);
});
// Listen for the 'close' event on the Express.js server
server.on('close', () => {
// Close the connection
questionRepo.close();
});
module.exports = server