Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Funcionalidad de historial de preguntas (guardarlas , recuperarlas e imprimirlas) #82

Merged
merged 5 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,21 @@ services:
networks:
- mynetwork
environment:
MONGODB_URI: mongodb://mongodb:27017/userdb
MONGODB_URI: mongodb://mongodb:27017/questiondb

retrieveservice:
container_name: retrieveservice-${teamname:-defaultASW}
image: ghcr.io/arquisoft/wiq_es2b/retrieveservice:latest
profiles: ["dev", "prod"]
build: ./questions/retrieveservice
depends_on:
- mongodb
ports:
- "8004:8004"
networks:
- mynetwork
environment:
MONGODB_URI: mongodb://mongodb:27017/questiondb

authservice:
container_name: authservice-${teamname:-defaultASW}
Expand Down Expand Up @@ -63,6 +77,7 @@ services:
- userservice
- authservice
- creationservice
- retrieveservice
ports:
- "8000:8000"
networks:
Expand All @@ -71,6 +86,7 @@ services:
AUTH_SERVICE_URL: http://authservice:8002
USER_SERVICE_URL: http://userservice:8001
CREATION_SERVICE_URL: http://creationservice:8005
RETRIEVE_SERVICE_URL: http://retrieveservice:8004

webapp:
container_name: webapp-${teamname:-defaultASW}
Expand Down
15 changes: 12 additions & 3 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,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 creationServiceUrl = process.env.CREATION_SERVICE_URL || 'http://localhost:8005';
const retrieveServiceUrl = process.env.RETRIEVE_SERVICE_URL || 'http://localhost:8004';

app.use(cors());
app.use(express.json());
Expand Down Expand Up @@ -43,10 +44,18 @@ app.post('/adduser', async (req, res) => {
app.post('/createquestion', async (req, res) => {
try {
// 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);
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 });
}
});

app.post('/getquestionshistory', async (req, res) => {
try {
// Create a petition to the URL (le llegará a retrieve-service.js) with the option /getgeneratedquestions and the req.body params
const questionResponse = await axios.post(retrieveServiceUrl+'/getquestionshistory', req.body);
// Return a json response with what we obtained on the petition
res.json(questionResponse.data);
} catch (error) {
Expand Down
25 changes: 20 additions & 5 deletions questions/creationservice/creation-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,26 @@ const mongoose = require('mongoose');

// Crea la base de datos con las columnas especificadas
const questionSchema = new mongoose.Schema({
question: String,
correctAnswer: String,
incorrectAnswer1: String,
incorrectAnswer2: String,
incorrectAnswer3: String,
question: {
type: String,
required: true,
},
correctAnswer: {
type: String,
required: true,
},
incorrectAnswer1: {
type: String,
required: true,
},
incorrectAnswer2: {
type: String,
required: true,
},
incorrectAnswer3: {
type: String,
required: true,
},
});

const Question = mongoose.model('Question', questionSchema);
Expand Down
34 changes: 31 additions & 3 deletions questions/creationservice/creation-service.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
const express = require('express');
const mongoose = require('mongoose');
const fetch = require('node-fetch');
const Question = require('./creation-model');

const app = express();
const port = 8005;

app.use(express.json());

const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/questiondb';
mongoose.connect(mongoUri);

const optionsNumber = 4;

// It will be the country of the question
// It will be the questionObject
var questionObject= "";
// It will be the correct capital of the question
// It will be the correct answer
var correctOption = "";
// It will be the different options for the answers
var answerOptions = [];
Expand All @@ -22,7 +26,7 @@ var queries = ['SELECT DISTINCT ?questionObject ?questionObjectLabel ?answer ?an
// Array of the possible questions
var questions = ["¿Cual es la capital de "];

// Recieves the information of the query and select wich data use on the question (country and capitals)
// Recieves the information of the query and select wich data use on the question
function getQuestionInfo(info){
answerOptions = [];
var fourRows = [];
Expand All @@ -47,6 +51,28 @@ function selectRandomQuery(){
randomQuerySelector = Math.floor(Math.random() * queries.length);
}

async function saveQuestion(){
var incorrectAnswers=[];
answerOptions.forEach(e => {
if(e!=correctOption)
incorrectAnswers.push(e);
});

try {
const newQuestion = new Question({
question: questionObject,
correctAnswer: correctOption,
incorrectAnswer1: incorrectAnswers[0],
incorrectAnswer2: incorrectAnswers[1],
incorrectAnswer3: incorrectAnswers[2]
});
await newQuestion.save();

}catch (error){
console.error("Error al guardar la pregunta: " + error);
}
}

app.post('/createquestion', async (req, res) => {
selectRandomQuery();
const apiUrl = `https://query.wikidata.org/sparql?query=${encodeURIComponent(queries[randomQuerySelector])}&format=json`;
Expand Down Expand Up @@ -77,6 +103,8 @@ app.post('/createquestion', async (req, res) => {
responseCorrectOption : correctOption,
responseAnswerOptions : answerOptions
};

saveQuestion();

// Return the resoult with a 200 status
res.status(200).json(solution);
Expand Down
2 changes: 1 addition & 1 deletion questions/creationservice/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "creationservice",
"version": "1.0.0",
"description": " Creation service, in charge of ",
"description": " Creation service, in charge of create the questions of the game and store them",
"main": "service.js",
"scripts": {
"start": "node creation-service.js",
Expand Down
2 changes: 2 additions & 0 deletions questions/retrieveservice/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
coverage
20 changes: 20 additions & 0 deletions questions/retrieveservice/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Use an official Node.js runtime as a parent image
FROM node:20

# Set the working directory in the container
WORKDIR /usr/src/retrieveservice

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install app dependencies
RUN npm install

# Copy the app source code to the working directory
COPY . .

# Expose the port the app runs on
EXPOSE 8004

# Define the command to run your app
CMD ["node", "retrieve-service.js"]
32 changes: 32 additions & 0 deletions questions/retrieveservice/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "retrieveservice",
"version": "1.0.0",
"description": " Retrieve service, in charge of claim the questions information stored on de database",
"main": "service.js",
"scripts": {
"start": "node retrieve-service.js",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/arquisoft/wiq_es2b.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/arquisoft/wiq_es2b/issues"
},
"homepage": "https://github.com/arquisoft/wiq_es2b#readme",
"dependencies": {
"bcrypt": "^5.1.1",
"body-parser": "^1.20.2",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.4"
},
"devDependencies": {
"jest": "^29.7.0",
"mongodb-memory-server": "^9.1.5",
"supertest": "^6.3.4"
}
}
14 changes: 14 additions & 0 deletions questions/retrieveservice/questionshistory-model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const mongoose = require('mongoose');

// Crea la base de datos con las columnas especificadas
const questionSchema = new mongoose.Schema({
question: String,
correctAnswer: String,
incorrectAnswer1: String,
incorrectAnswer2: String,
incorrectAnswer3: String
});

const Question = mongoose.model('Question', questionSchema);

module.exports = Question
33 changes: 33 additions & 0 deletions questions/retrieveservice/retrieve-service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const express = require('express');
const mongoose = require('mongoose');
const Question = require('./questionshistory-model')

const app = express();
const port = 8004;

app.use(express.json());

const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/questiondb';
mongoose.connect(mongoUri);


app.post('/getquestionshistory', async (req, res) => {
const questions = await Question.find({});

var solution = [];
questions.forEach(row => {
solution.push([row.question,row.correctAnswer,row.incorrectAnswer1,row.incorrectAnswer2,row.incorrectAnswer3]);
});

res.status(200).json(solution);
});

const server = app.listen(port, () => {
console.log(`Creation Service listening at http://localhost:${port}`);
});

server.on('close', () => {
mongoose.connection.close();
});

module.exports = server;
33 changes: 13 additions & 20 deletions webapp/src/components/Game.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Container, Typography, Button, Paper, TimerIcon } from '@mui/material';
import { Container, Typography, Button, Paper} from '@mui/material';

import './Game.css';

Expand All @@ -15,6 +15,7 @@ const Game = () => {
const [correctOption, setCorrectOption] = useState('');
const [answerOptions, setAnswerOptions] = useState([]);
const [correctCounter, setCorrectCounter] = useState(0);
const [numberOfOptions, setNumberOfOptions] = useState();

const [questionCounter, setQuestionCounter] = useState(0);
const [incorrectCounter, setIncorrectCounter] = useState(0);
Expand Down Expand Up @@ -63,7 +64,6 @@ const Game = () => {
// 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 === correctOption) {
const buttonId = `button_${index}`;
const correctButton = document.getElementById(buttonId);
Expand Down Expand Up @@ -109,15 +109,15 @@ const Game = () => {
Saber y Ganar Juego
</Typography>
<Typography variant="body1" paragraph>
Pregunta {questionCounter}: ¿Cuál es la capital de {questionObject}?
Pregunta {questionCounter}: {questionObject}
</Typography>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', alignItems: 'center', marginTop: '2em' }}>
{answerOptions.map((option, index) => (
<Button id={`button_${index}`} title="btnsPreg" key={index} variant="contained" color="primary" onClick={() => handleAnswerClick(option,index)} >
{option}
</Button>
))}
</div>
{answerOptions.map((option, index) => (
<Button id={`button_${index}`} title="btnsPreg" key={index} variant="contained" color="primary" onClick={() => handleAnswerClick(option,index)} >
{option}
</Button>
))}
</div>
</Paper>

<Button title="contador" onMouseEnter={null} variant="contained" color="primary" disabled={true}>
Expand All @@ -129,20 +129,13 @@ const Game = () => {
</Button>

<div>
<svg data-testid="TimerIcon"></svg>

<svg data-testid="TimerIcon"></svg>

<div>
<span>Time Remaining: {Math.floor(seconds / 60)}:{(seconds % 60).toLocaleString('en-US', { minimumIntegerDigits: 2 })}</span>
</div>
<div>
<span>Time Remaining: {Math.floor(seconds / 60)}:{(seconds % 60).toLocaleString('en-US', { minimumIntegerDigits: 2 })}</span>
</div>
</div>


{/* <Button title="sigPreg" variant="contained" color="primary" onClick={handleShowQuestion}>
Siguiente pregunta
</Button> */}


</Container>
);
};
Expand Down
Loading