From 7dc77a8b5baa70ab8211f357fcf6fd9b5843be6f Mon Sep 17 00:00:00 2001 From: baraganio Date: Tue, 5 Mar 2024 20:10:12 +0100 Subject: [PATCH 1/2] Changes on the creation-service, now it returns one country, its capital and four posible ones --- gatewayservice/gateway-service.js | 14 +-- questions/creationservice/creation-service.js | 107 +++++++++--------- webapp/src/components/Game.js | 10 +- 3 files changed, 62 insertions(+), 69 deletions(-) diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index 945d2a97..6d38f474 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -24,10 +24,7 @@ app.get('/health', (_req, res) => { app.post('/login', async (req, res) => { try { - // Crea una peticion a la url (le llegará a auth-service.js) con la opcion /login - // y los parametros req.body const authResponse = await axios.post(authServiceUrl+'/login', req.body); - // Almacena en un Json la respuesta de la anterior peticion res.json(authResponse.data); } catch (error) { res.status(error.response.status).json({ error: error.response.data.error }); @@ -36,10 +33,7 @@ app.post('/login', async (req, res) => { app.post('/adduser', async (req, res) => { try { - // Crea una peticion a la url (le llegará a user-service.js) con la opcion /login - // y los parametros req.body const userResponse = await axios.post(userServiceUrl+'/adduser', req.body); - // Almacena en un Json la respuesta de la anterior peticion res.json(userResponse.data); } catch (error) { res.status(error.response.status).json({ error: error.response.data.error }); @@ -48,10 +42,12 @@ app.post('/adduser', async (req, res) => { app.post('/createquestion', async (req, res) => { try { - // Crea una peticion a la url (le llegará a creation-service.js) con la opcion /login - // y los parametros req.body + // Create a petition to the URL (le llegará a creation-service.js) with the option /createquestion and the req.body params + console.log("salgo de gateway hacia creation"); const questionResponse = await axios.post(creationServiceUrl+'/createquestion', req.body); - // Almacena en un Json la respuesta de la anterior peticion + console.log("vengo de creation y estoy en gateway"); + console.log(questionResponse.status); + // Return a json response with what we obtained on the petition res.json(questionResponse.data); } catch (error) { res.status(error.response.status).json({ error: error.response.data.error }); diff --git a/questions/creationservice/creation-service.js b/questions/creationservice/creation-service.js index 47563896..3ff39200 100644 --- a/questions/creationservice/creation-service.js +++ b/questions/creationservice/creation-service.js @@ -7,67 +7,68 @@ const port = 8005; app.use(express.json()); -const query = async (SPARQL) => { - const apiUrl = `https://query.wikidata.org/sparql?query=${encodeURIComponent(SPARQL)}&format=json`; - - const response = await fetch(apiUrl, { - headers: { - 'Accept': 'application/json' - } - }); - - if (!response.ok) { - console.error('Error al realizar la consulta a Wikidata:', response.statusText); - return; +// It will be the country of the question +var country= ""; +// It will be the correct capital of the question +var capitalCorrect = ""; +// It will be the different options for the answers +var capitalOptions = []; + +// Recieves the information of the query and select wich data use on the question (country and capitals) +function getQuestionInfo(info){ + capitalOptions = []; + fourRows = []; + const numEles = info.length; + + // Select 4 random rows of the data + for (let i = 0; i<4; i++){ + var indexRow = Math.floor(Math.random() * numEles); + fourRows.push(info[indexRow]); + // Store the 4 posible answers + capitalOptions.push(info[indexRow].capitalLabel.value); } - - const datos = await response.json(); - - const resultados = datos.results.bindings.map((resultado) => { - const resultadoFormateado = {}; - Object.keys(resultado).forEach((clave) => { - resultadoFormateado[clave] = resultado[clave].value; - }); - - return resultadoFormateado; - }); - - return resultados; -}; - -const surroundWithCache = (func) => { - let cache = {}; - - return async (param) => { - if (param in cache) { - return cache[param]; - } - - let res = await func(param); - - cache[param] = res; - - return res; - }; -}; - -const cachedQuery = surroundWithCache(query); + + // Select the row where it will extract the country and capital + const indexQuestion = Math.floor(Math.random() * 4); + // Store the country choosen and its capital + country=fourRows[indexQuestion].countryLabel.value; + capitalCorrect = fourRows[indexQuestion].capitalLabel.value; +} app.post('/createquestion', async (req, res) => { const sparqlQuery = 'SELECT DISTINCT ?country ?countryLabel ?capital ?capitalLabel WHERE { ?country wdt:P31 wd:Q6256. ?country wdt:P36 ?capital. SERVICE wikibase:label {bd:serviceParam wikibase:language "[AUTO_LANGUAGE],es".}}'; + const apiUrl = `https://query.wikidata.org/sparql?query=${encodeURIComponent(sparqlQuery)}&format=json`; try { - const data = await cachedQuery(sparqlQuery); - const numEles = data.length; - if (numEles > 0) { - const index = Math.floor(Math.random() * numEles); - const result = data[index]; - res.json(result); - } else { - console.log('No se encontraron resultados en Wikidata.'); - res.status(404).json({ error: 'No se encontraron resultados en Wikidata.' }); + // Makes the petition to the url + const response = await fetch(apiUrl, { + headers: { + 'Accept': 'application/json' + } + }); + + // Check if everything was good on the petition + if (!response.ok) { + console.error('Error al realizar la consulta a Wikidata:', response.statusText); + return; } + + // Parse the response + const data = await response.json(); + + // Send the parsed response to be selected + getQuestionInfo(data.results.bindings); + + // Declare what will be return + solution = { + responseCountry : country, + responseCapitalCorrect : capitalCorrect, + responseCapitalOptions : capitalOptions + }; + + // Return the resoult with a 200 status + res.status(200).json(solution); } catch (error) { console.error('Error al realizar la consulta:', error); res.status(500).json({ error: 'Internal Server Error' }); diff --git a/webapp/src/components/Game.js b/webapp/src/components/Game.js index d1b710a5..6dab9e22 100644 --- a/webapp/src/components/Game.js +++ b/webapp/src/components/Game.js @@ -11,15 +11,11 @@ const Game = () => { const [capitalIcnorrecta2, setcapitalIcnorrecta2] = useState(''); const [capitalIcnorrecta3, setcapitalIcnorrecta3] = useState(''); - // Esta es la llamada al servicio de generar las preguntas + // This method will call the create question service const handleShowQuestion = async () => { try{ - // Se declara esta variable unicamente para probar cosas con ella en la peticion - const eyou = "aa" - // Se hace una peticion a la api (llega a gateway-service.js) con la opcion createquestion - // y los parametros de entrada aa, aa - const response = await axios.post(`${apiEndpoint}/createquestion`, { eyou, eyou }); - console.log(response); + // It makes a petition to the api and store the response + const response = await axios.post(`${apiEndpoint}/createquestion`, { }); }catch (error){ console.error('Error:', error); } From dce489954656c21dc8aaf786c7f3aed103ac9c18 Mon Sep 17 00:00:00 2001 From: baraganio Date: Tue, 5 Mar 2024 21:14:13 +0100 Subject: [PATCH 2/2] Configured the buttoms of the game to show all the posible options and check if the pressed is the correct one or no --- webapp/src/components/Game.js | 73 +++++++++++++---------------------- 1 file changed, 27 insertions(+), 46 deletions(-) diff --git a/webapp/src/components/Game.js b/webapp/src/components/Game.js index 6dab9e22..b8525999 100644 --- a/webapp/src/components/Game.js +++ b/webapp/src/components/Game.js @@ -1,3 +1,4 @@ + import React, { useState } from 'react'; import axios from 'axios'; import { Container, Typography, Button, Paper } from '@mui/material'; @@ -5,45 +6,34 @@ import { Container, Typography, Button, Paper } from '@mui/material'; const Game = () => { const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000'; - const [pais, setpais] = useState(''); - const [capitalCorrecta, setcapital] = useState(''); - const [capitalIcnorrecta1, setcapitalIcnorrecta1] = useState(''); - const [capitalIcnorrecta2, setcapitalIcnorrecta2] = useState(''); - const [capitalIcnorrecta3, setcapitalIcnorrecta3] = useState(''); + const [country, setCountry] = useState(''); + const [capitalCorrect, setCapitalCorrect] = useState(''); + const [capitalOptions, setcapitalOptions] = useState([]); // This method will call the create question service const handleShowQuestion = async () => { try{ // It makes a petition to the api and store the response const response = await axios.post(`${apiEndpoint}/createquestion`, { }); + // Extract all the info of the response and store it + setCountry(response.data.responseCountry); + setCapitalCorrect(response.data.responseCapitalCorrect); + setcapitalOptions(response.data.responseCapitalOptions); }catch (error){ console.error('Error:', error); } } - // TODO ESTO ES LO QUE ESTA COMENTADO EN CREATION-SERVICE.JS - // CREO QUE DEBERIA IR ALLI PERO COMO NO FUNCIONA LO PROBE AQUI - const deberiaIrEnelServicio = async () => { - const sparqlQuery = 'SELECT DISTINCT ?country ?countryLabel ?capital ?capitalLabel WHERE { ?country wdt:P31 wd:Q6256. ?country wdt:P36 ?capital. SERVICE wikibase:label {bd:serviceParam wikibase:language "[AUTO_LANGUAGE],es".}}'; - const apiUrl = `https://query.wikidata.org/sparql?query=${encodeURIComponent(sparqlQuery)}`; - const headers = { "Accept": "application/json" } - const respuestaWikidata = await fetch(apiUrl, {headers}); - if (respuestaWikidata.ok) { - const data = await respuestaWikidata.json(); - const numEles = data.results.bindings.length; - const indexCapCorre = Math.floor(Math.random() * numEles); - const result = data.results.bindings[indexCapCorre]; - setpais(result.countryLabel.value); - setcapital(result.capitalLabel.value); - - const indexCapIncorre1 = Math.floor(Math.random() * numEles); - const indexCapIncorre2 = Math.floor(Math.random() * numEles); - const indexCapIncorre3 = Math.floor(Math.random() * numEles); - setcapitalIcnorrecta1(data.results.bindings[indexCapIncorre1].capitalLabel.value); - setcapitalIcnorrecta2(data.results.bindings[indexCapIncorre2].capitalLabel.value); - setcapitalIcnorrecta3(data.results.bindings[indexCapIncorre3].capitalLabel.value); - } else { - console.error("Error al realizar la consulta en Wikidata. Estado de respuesta:", respuestaWikidata.status); + // Method that checks if the answer clicked is the correct one + const handleAnswerClick = (option, index) => { + // Get what component is the button to change its color later + //const button = document.getElementById(`button_${index}`); + if(option === capitalCorrect){ + //button.style.backgroundColor = "green"; + alert("CORRECTO"); + }else{ + //button.style.backgroundColor = "red"; + alert("INCORRECTO"); } } @@ -54,27 +44,18 @@ const Game = () => { Saber y Ganar Juego - Pregunta: ¿Cuál es la capital de {pais}? + Pregunta: ¿Cuál es la capital de {country}? - {/* Botones de opción */} - - - - +
+ {capitalOptions.map((option, index) => ( + + ))} +
- );