Skip to content

Commit

Permalink
Refactorización de question-service.js y Modularización del Código
Browse files Browse the repository at this point in the history
  • Loading branch information
Verzidee committed Feb 26, 2024
1 parent 27a10ea commit ff12db9
Show file tree
Hide file tree
Showing 5 changed files with 154 additions and 0 deletions.
15 changes: 15 additions & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const port = 8000;

const authServiceUrl = process.env.AUTH_SERVICE_URL || 'http://localhost:8002';
const userServiceUrl = process.env.USER_SERVICE_URL || 'http://localhost:8001';
const generateServiceURL = process.env.GENERATE_SERVICE_URL || 'http://localhost:8003';

app.use(cors());
app.use(express.json());
Expand Down Expand Up @@ -41,6 +42,20 @@ app.post('/adduser', async (req, res) => {
}
});

app.post('/getquestion', async(req,res)=> {
try{
// Redirige la solicitud al servicio de generación de preguntas sin enviar un cuerpo de solicitud.
const response = await axios.post(`${generateServiceURL}/getquestion`);

// Devuelve la respuesta del servicio de generación de preguntas al cliente original.
res.json(response.data);

} catch(error) {
res.status(error.response.status).json({ error: error.response.data.error });
}
});


// Start the gateway service
const server = app.listen(port, () => {
console.log(`Gateway Service listening at http://localhost:${port}`);
Expand Down
29 changes: 29 additions & 0 deletions questionservice/question-service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const express = require('express');
const app = express();
const port = 8003;

// Importamos la función desde questionTemplates.js
const getQuestionTemplate = require('./questionTemplates');

app.use(express.json());

app.post('/getquestion', async (req, res) => {
try {
const questionAndAnswer = await getQuestionTemplate(); // Obtenemos el json de pregunta y sus respuestas

if (questionAndAnswer) {
res.json(questionAndAnswer); //Devolvemos a la gateway el json
} else {
// Si no se obtuvo una pregunta por alguna razón, enviamos un error genérico
res.status(500).json({ error: "Could not get a question and answers" });
}
} catch (error) {
// En caso de cualquier error en el proceso, lo capturamos y enviamos un mensaje de error
console.error("Error generating question:", error);
res.status(500).json({ error: "Internal server error when generating the question" });
}
});

app.listen(port, () => {
console.log(`Server listening on http://localhost:${port}`);
});
33 changes: 33 additions & 0 deletions questionservice/questionTemplates.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const wikiQuery = require("./wikiUtils/wikiQuery")

const templates = [
async () => {
const country = await wikiQuery.getRandomCountryAndCity();
//Obtenemos los fakeCities
const fakeCities = await wikiQuery.getFakeCity(country.capital);
const correctAnswer = { answer: country.capital, correct: true };
const fakeAnswers = fakeCities.map(city => ({ answer: city, correct: false }));
const answers = [correctAnswer, ...fakeAnswers];

// 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
};
},
// Aquí podemos añadir más templates
];

// Función para mezclar las respuestas
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}

// Seleccionamos aleatoriamente un template y lo ejecutamos
module.exports = () => templates[Math.floor(Math.random()*templates.length)]();
22 changes: 22 additions & 0 deletions questionservice/wikiUtils/wikiCall.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const fetch = require('node-fetch');

const ENDPOINT_URL = 'https://query.wikidata.org/sparql';

async function wikiCall(sparqlQuery) {
const url = ENDPOINT_URL + '?query=' + encodeURIComponent(sparqlQuery);
const headers = { 'Accept': 'application/sparql-results+json' };

try {
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.results.bindings;
} catch (error) {
console.error(`Could not fetch data from Wikidata: ${error}`);
return [];
}
}

module.exports = wikiCall;
55 changes: 55 additions & 0 deletions questionservice/wikiUtils/wikiQuery.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const wikiCall = require("./wikiCall");

//Selecionar un resultado de las consultas aleatorio
const randomElement = (items) => items[Math.floor(Math.random() * items.length)];

class wikiQuery {

static async getRandomCountryAndCity() {
const query = `
SELECT ?country ?countryLabel ?capitalLabel WHERE {
?country wdt:P31 wd:Q6256; # Tipo de entidad: País
wdt:P36 ?capital. # Propiedad: Tiene por capital
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],es". }
}
LIMIT 50`;

const results = randomElement(await wikiCall(query));

return {
name: results['countryLabel'].value,
capital: results['capitalLabel'].value
};
}

static async getRandomCity() {
const query = `
SELECT ?city ?cityLabel WHERE {
?city wdt:P31 wd:Q515; # Tipo de entidad: Ciudad
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],es". }
}
LIMIT 50`;


const results = randomElement(await wikiCall(query));

return results['cityLabel'].value;

}
static async getFakeCity(capital) {
let Fakecitys = [];

while(Fakecitys.length < 3) {
let randomCity = await this.getRandomCity();
if(randomCity !== capital && !Fakecitys.includes(randomCity)) {
Fakecitys.push(randomCity);
}
}

return Fakecitys;
}


}

module.exports = wikiQuery

0 comments on commit ff12db9

Please sign in to comment.