Skip to content

Commit

Permalink
Ya funciona toda la configuración
Browse files Browse the repository at this point in the history
  • Loading branch information
CANCI0 committed Mar 13, 2024
1 parent 610b330 commit 82dc0b4
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 29 deletions.
44 changes: 28 additions & 16 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,12 +14,19 @@ 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();
});
Expand All @@ -43,17 +50,21 @@ app.get("/questions", async (req, res) => {
});

app.post("/questions", async (req, res) => {
if (req.body.n > MAX_QUESTIONS) {
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 {
console.log(req.body.tematicas)
var temp = JSON.parse(req.body.tematicas)
var tematicas = temp.length !== 0 ? temp : ["paises", "literatura", "cine", "arte", "programacion"];
var n = req.body.n ? req.body.n : 10;
var data = gen.getQuestionsPost(tematicas, n);
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 });
Expand All @@ -62,14 +73,15 @@ app.post("/questions", async (req, res) => {

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
3 changes: 3 additions & 0 deletions webapp/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ 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
4 changes: 2 additions & 2 deletions webapp/src/pages/Clasico/Clasico.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Footer from "../../components/Footer/Footer.js";

const JuegoPreguntas = () => {
const URL = process.env.REACT_APP_API_ENDPOINT || "http://localhost:8000";
const SECS_PER_QUESTION = useMemo(localStorage.getItem("clasicoTime"));
const SECS_PER_QUESTION = useMemo(() => localStorage.getItem("clasicoTime"));

const [isLoading, setIsLoading] = useState(true);
const [indicePregunta, setIndicePregunta] = useState(0);
Expand All @@ -33,7 +33,7 @@ const JuegoPreguntas = () => {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ tematicas: localStorage.getItem("selectedThemes"), n: 10 }),
body: JSON.stringify({ tematicas: localStorage.getItem("selectedThemes"), n: localStorage.getItem("clasicoPreguntas") })
})
.then((response) => {
if (!response.ok) {
Expand Down
34 changes: 28 additions & 6 deletions webapp/src/pages/Config/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,15 @@ import Footer from "../../components/Footer/Footer.js";
const Config = () => {
const [error, setError] = useState("");
const [info, setInfo] = useState("");
const [clasicoTime, setClasicoTime] = useState(10);
const [bateriaTime, setBateriaTime] = useState(180);
const [clasicoTime, setClasicoTime] = useState(
localStorage.getItem("clasicoTime")
);
const [clasicoPreguntas, setClasicoPreguntas] = useState(
localStorage.getItem("clasicoPreguntas")
);
const [bateriaTime, setBateriaTime] = useState(
localStorage.getItem("bateriaTime")
);

const handleConfig = () => {
const checkboxes = document.querySelectorAll(
Expand All @@ -26,6 +33,7 @@ const Config = () => {
} else {
localStorage.setItem("selectedThemes", JSON.stringify(selectedThemes));
localStorage.setItem("clasicoTime", clasicoTime);
localStorage.setItem("clasicoPreguntas", clasicoPreguntas);
localStorage.setItem("bateriaTime", bateriaTime);

alert("Cambios realizados satisfactoriamente");
Expand All @@ -36,6 +44,10 @@ const Config = () => {
setClasicoTime(parseInt(event.target.value));
};

const handleClasicoPreguntas = (event) => {
setClasicoPreguntas(parseInt(event.target.value));
};

const handleBateriaChange = (event) => {
setBateriaTime(parseInt(event.target.value));
};
Expand All @@ -62,9 +74,8 @@ const Config = () => {
<label htmlFor="programacion"> Programación</label>
<input id="programacion" type="checkbox" />
</div>
<h3>Tiempo</h3>
<div>
<label htmlFor="clasico"> Clásico (entre preguntas)</label>
<label htmlFor="clasico"> Tiempo entre preguntas (Clásico)</label>
<input
id="clasico"
value={clasicoTime}
Expand All @@ -73,8 +84,19 @@ const Config = () => {
max="20"
onChange={handleClasicoChange}
/>

<label htmlFor="bateria"> Batería de sabios (Tiempo total)</label>
<label htmlFor="clasicoPreguntas">
{" "}
Número de preguntas (Clásico)
</label>
<input
id="clasicoPreguntas"
value={clasicoPreguntas}
type="number"
min="1"
max="1000"
onChange={handleClasicoPreguntas}
/>
<label htmlFor="bateria">Tiempo total (Batería de sabios)</label>
<input
id="bateria"
value={bateriaTime}
Expand Down

0 comments on commit 82dc0b4

Please sign in to comment.