Skip to content

Commit

Permalink
Merge pull request #65 from Arquisoft/Configuración
Browse files Browse the repository at this point in the history
Configuración
  • Loading branch information
CANCI0 authored Mar 13, 2024
2 parents 534754d + 82dc0b4 commit 22316ca
Show file tree
Hide file tree
Showing 13 changed files with 298 additions and 308 deletions.
15 changes: 15 additions & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,21 @@ app.get("/questions", async (req, res) => {
}
});

app.post("/questions", async (req, res) => {
try {
// Forward the question request to the question service
const questionResponse = await axios.post(
questionServiceUrl + "/questions",
{ body: req.body }
);
res.json(questionResponse.data);
} catch (error) {
res
.status(error.response.status)
.json({ error: error.response.data.error });
}
});

app.get("/stats", async (req, res) => {
try {
// Forward the stats request to the stats service
Expand Down
51 changes: 40 additions & 11 deletions questionservice/question-service.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// user-service.js
const express = require("express");
const cors = require('cors');
const cors = require("cors");
const bodyParser = require("body-parser");
const cron = require("node-cron");
const GeneratorChooser = require("./questionGen/GeneratorChooser");
Expand All @@ -14,20 +14,26 @@ const MAX_QUESTIONS = 10000;

// Middleware to parse JSON in request body
app.use(bodyParser.json());
// support encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cors());

app.use((req, res, next) => {
if (!generadoresCargados) {
return res.status(500).json({ error: "Los generadores de preguntas aún no se han cargado. Por favor, inténtalo de nuevo más tarde." });
return res
.status(500)
.json({
error:
"Los generadores de preguntas aún no se han cargado. Por favor, inténtalo de nuevo más tarde.",
});
}
next();
});

app.set("json spaces", 40);

app.get("/questions", async (req, res) => {
console.log(req.query)
if (req.query.n > MAX_QUESTIONS) {
res
.status(400)
Expand All @@ -43,16 +49,39 @@ app.get("/questions", async (req, res) => {
}
});

app.post("/questions", async (req, res) => {
const { tematicas, n } = req.body.body;
if (!n || n > MAX_QUESTIONS) {
res
.status(400)
.json({ error: `El límite de preguntas son ${MAX_QUESTIONS}` });
return;
}
try {
const temas = tematicas ? JSON.parse(tematicas) : [];
const tematicasValidas =
temas.length !== 0
? temas
: ["paises", "literatura", "cine", "arte", "programacion"];
const cantidadPreguntas = parseInt(n, 10);
const data = gen.getQuestionsPost(tematicasValidas, cantidadPreguntas);
res.json(data);
} catch (error) {
res.status(400).json({ error: error.message });
}
});

const server = app.listen(port, async () => {
console.log(`Question Service listening at http://localhost:${port}`);
gen.loadGenerators()
.then(() => {
console.log("Generators loaded successfully!");
generadoresCargados = true;
})
.catch((error) => {
console.error("Error al cargar los generadores de preguntas:", error);
});
gen
.loadGenerators()
.then(() => {
console.log("Generators loaded successfully!");
generadoresCargados = true;
})
.catch((error) => {
console.error("Error al cargar los generadores de preguntas:", error);
});
});

cron.schedule("0 3 * * *", async () => {
Expand Down
103 changes: 60 additions & 43 deletions questionservice/questionGen/GeneratorChooser.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,70 @@
const GenericGenerator = require('./GenericGenerator')
const fs = require('fs');

class GeneratorChooser{
constructor(){
this.generators = new Map();
this.tematicas = [];
this.leer_json("./data/tematicas.json");
}
const GenericGenerator = require("./GenericGenerator");
const fs = require("fs");

class GeneratorChooser {
constructor() {
this.generators = new Map();
this.tematicas = [];
this.leer_json("./data/tematicas.json");
}

leer_json(ruta){
const datos = fs.readFileSync(ruta);
var tematicas = JSON.parse(datos);

for(let i in tematicas){
var tematica = tematicas[i];
this.tematicas.push(i);
this.generators.set(i,
new GenericGenerator(tematica.entity, tematica.props, tematica.types, tematica.preguntas)
);
}
leer_json(ruta) {
const datos = fs.readFileSync(ruta);
var tematicas = JSON.parse(datos);

for (let i in tematicas) {
var tematica = tematicas[i];
this.tematicas.push(i);
this.generators.set(
i,
new GenericGenerator(
tematica.entity,
tematica.props,
tematica.types,
tematica.preguntas
)
);
}
}

getQuestions(tematica, n){
if(tematica === "all"){
var questions = [];
for(let i = 0 ; i < n ; i++){
let rand = Math.floor(Math.random() * this.tematicas.length)
let randTematica =this.tematicas[rand];
let q = this.generators.get(randTematica).generateRandomQuestions(1);
questions.push(q);
}
return questions.flat();
}else{
return this.generators.get(tematica).generateRandomQuestions(n);
}
getQuestions(tematica, n) {
if (tematica === "all") {
var questions = [];
for (let i = 0; i < n; i++) {
let rand = Math.floor(Math.random() * this.tematicas.length);
let randTematica = this.tematicas[rand];
let q = this.generators.get(randTematica).generateRandomQuestions(1);
questions.push(q);
}
return questions.flat();
} else {
return this.generators.get(tematica).generateRandomQuestions(n);
}
}

async loadGenerators(){
for(let i = 0 ; i < this.tematicas.length ; i++){
var gen = this.generators.get(this.tematicas[i]);
console.log("Cargando temática: " + this.tematicas[i]);
await gen.getData();
await this.#sleep(10000);
}
getQuestionsPost(tematicas, n) {
var questions = [];
for (let i = 0; i < n; i++) {
let rand = Math.floor(Math.random() * tematicas.length);
let randTematica = tematicas[rand];
let q = this.generators.get(randTematica).generateRandomQuestions(1);
questions.push(q);
}
return questions.flat();
}

#sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
async loadGenerators() {
for (let i = 0; i < this.tematicas.length; i++) {
var gen = this.generators.get(this.tematicas[i]);
console.log("Cargando temática: " + this.tematicas[i]);
await gen.getData();
await this.#sleep(10000);
}
}

#sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}

module.exports = GeneratorChooser;
module.exports = GeneratorChooser;
2 changes: 2 additions & 0 deletions webapp/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import "./App.css";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { ProtectedRoute } from "./routers/ProtectedRoute.js";
import Sobre from "./pages/Sobre/Sobre.js";
import Config from "./pages/Config/Config.js";

function App() {
return (
Expand All @@ -25,6 +26,7 @@ function App() {
<Route path="/home/clasico" element={<Clasico />} />
<Route path="/home/bateria" element={<Bateria />} />
<Route path="/stats" element={<Stats />} />
<Route path="/config" element={<Config />} />
</Route>

{/* Ruta por defecto */}
Expand Down
6 changes: 5 additions & 1 deletion webapp/src/components/Nav/Nav.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ const Nav = () => {
setIsDarkTheme((prev) => !prev);
};

const handleConfig = () => {
navigate("/config");
}

const Logout = () => {
localStorage.removeItem("token");
navigate("/");
Expand All @@ -40,7 +44,7 @@ const Nav = () => {
<button className="profile">
Perfil
</button>
<button className="profile">
<button className="profile" onClick={() => handleConfig()}>
Opciones
</button>
<button className="disconnect" onClick={() => Logout()}>
Expand Down
32 changes: 0 additions & 32 deletions webapp/src/components/PreguntasConceCiudades.js

This file was deleted.

4 changes: 4 additions & 0 deletions webapp/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import reportWebVitals from './reportWebVitals';
var r = document.getElementById('root');
r.setAttribute("data-theme", "light")
const root = ReactDOM.createRoot(r);
localStorage.setItem("selectedThemes", JSON.stringify(["paises", "literatura", "cine", "arte", "programacion"]));
localStorage.setItem("clasicoTime", 10);
localStorage.setItem("clasicoPreguntas", 10);
localStorage.setItem("bateriaTime", 180);

root.render(
//<React.StrictMode>
Expand Down
16 changes: 11 additions & 5 deletions webapp/src/pages/Bateria/Bateria.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Link, useNavigate } from "react-router-dom";

const JuegoPreguntas = () => {
const URL = process.env.REACT_APP_API_ENDPOINT || "http://localhost:8000"
const TIME = 180;
const TIME = localStorage.getItem("bateriaTime");

const [isLoading, setIsLoading] = useState(true);
const [indicePregunta, setIndicePregunta] = useState(0);
Expand All @@ -19,11 +19,17 @@ const JuegoPreguntas = () => {
const navigate = useNavigate();

useEffect(() => {
fetch(URL + "/questions?tematica=all&n=9000")
fetch(URL + "/questions", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ tematicas: localStorage.getItem("selectedThemes"), n: 9000 }),
})
.then((response) => {
if (!response.ok) {
navigate("/home?error=1");
return;
throw new Error("Error en la solicitud");
}
return response.json();
})
Expand All @@ -36,8 +42,8 @@ const JuegoPreguntas = () => {
console.error("Error al obtener las preguntas:", error);
navigate("/home?error=1");
});
// eslint-disable-next-line
},[]);
// eslint-disable-next-line
}, []);

useEffect(() => {
if (tiempoRestante === 0) {
Expand Down
Loading

0 comments on commit 22316ca

Please sign in to comment.