generated from Arquisoft/wiq_0
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactorización de question-service.js y Modularización del Código
- Loading branch information
Showing
5 changed files
with
154 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)](); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |