Skip to content

Commit

Permalink
Added exceptions and param validation
Browse files Browse the repository at this point in the history
  • Loading branch information
AbelMH1 committed Apr 11, 2024
1 parent 70f010a commit e697ee1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,31 +25,44 @@ app.use(cors());
// Only parse query parameters into strings, not objects (adds security)
app.set('query parser', 'simple');

// Function to generate the required number of questions
async function getQuestions(req) {
const preguntas = req.query.n_preguntas || 1;
const respuestas = req.query.n_respuestas || 4;
var temas = req.query.tema || [];
function validateNumberInQuery(number, minValue, paramName, defValue) {
if (!(paramName in number)) return defValue;
n = Number(number[paramName]);
if (isNaN(n)) throw new Error(`A number was expected in param \'${paramName}\'`);
if (n < minValue) throw new Error(`\'${paramName}\' must be at least \'${minValue}\'`);
return n;
}

// Function to validate required fields in the request body
function validateFields(query) {
const preguntas = validateNumberInQuery(query, 1, 'n_preguntas', 1);
const respuestas = validateNumberInQuery(query, 1, 'n_respuestas', 4);
var temas = query.tema || [];
if (!Array.isArray(temas)) {
temas = Array.of(temas);
}

return await QuestionGenerator.generateQuestions(preguntas, respuestas, temas);
}
return { preguntas, respuestas, temas };
}

// Route for getting questions
app.get('/questions', async (req, res) => {
try {
const retQuestions = await getQuestions(req);
try{
const questionsHistoryResponse = await axios.post(questionHistoryServiceUrl + '/history/questions', retQuestions);
const { preguntas, respuestas, temas } = validateFields(req.query);
try {
const retQuestions = await QuestionGenerator.generateQuestions(preguntas, respuestas, temas);
try {
await axios.post(questionHistoryServiceUrl + '/history/questions', retQuestions);
} catch (error) {
console.error(`Error saving questions history: ${error}`);
}
res.json(retQuestions);
} catch (error) {
console.error(`Error saving questions history: ${error}`);
console.error(`An error occurred: ${error.message}`);
res.status(500).json({ error: 'Internal Server Error' });
}
res.json(retQuestions);
} catch (error) {
console.error(`An error occurred: ${error.message}`)
res.status(500).json({ error: 'Internal Server Error' });
console.error(`Bad Request: ${error.message}`);
res.status(400).json({ message: error.message });
}
});

Expand Down
15 changes: 14 additions & 1 deletion questionsservice/questiongeneratorservice/questiongenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,13 @@ class QuestionGenerator {

const randomDocs = await Pais.aggregate([
{ $match: plantilla.filtro },
{ $sample: { size: Number(respuestas) } }
{ $sample: { size: respuestas } }
]);
if (randomDocs.length < respuestas) {
console.error(`Not enought data found to generate a question`);
throw new Error(`Not enought data found to generate a question`);
}

console.log("\nFind:");
console.log(randomDocs);

Expand Down Expand Up @@ -75,7 +80,15 @@ class QuestionGenerator {
templates = templates.concat(this.temas.get(tema));
console.log(this.temas.get(tema));
}
else {
console.error(`The topic \'${tema}\' is not currently defined`);
throw new Error(`The topic \'${tema}\' is not currently defined`);
}
});
if (templates.length == 0) {
console.error(`No correct topics were passed`);
throw new Error(`No correct topics were passed`);
}
console.log(templates);
console.log([...new Set(templates)]);
return [...new Set(templates)];
Expand Down

0 comments on commit e697ee1

Please sign in to comment.