Skip to content

Commit

Permalink
Merge pull request #18 from pes2324q2-gei-upc/xats
Browse files Browse the repository at this point in the history
Afegir els tokens del foro
  • Loading branch information
Eman0209 authored May 1, 2024
2 parents 9d0ebbc + 67bb349 commit 308550a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 36 deletions.
83 changes: 48 additions & 35 deletions back_api/routes/foros.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ router.use(express.json());

const { db } = require('../firebaseConfig');

const checkUserAndFetchData = require('./middleware').checkUserAndFetchData;

//foro existe?
router.get('/exists', async (req, res) => {
try {
//console.log("Solicitud recibida en la ruta '/foros/exists'");

var activitatCode = req.query.activitat_code;
//console.log("Valor de activitat_code:", activitatCode);

const docRef = db.collection('foros').where('activitat_code', '==', activitatCode).limit(1);

Expand All @@ -22,42 +22,35 @@ router.get('/exists', async (req, res) => {
const data = snapshot.docs[0].data();
res.status(200).json({ "exists": true, "data": data });
} else {
// Si no existe ningún documento con el activitat_code dado, el foro no existe
// Si no existe ningún documento el foro no existe
res.status(200).json({ "exists": false });
}
})
.catch(error => {
//console.error("Error al consultar la base de datos:", error);
res.status(500).send("Error interno del servidor");
});
} catch (error) {
//console.error("Error en la ruta '/foros/exists':", error.message);
res.status(500).send("Error interno del servidor");
}
});

//crear foro
router.post('/create', async(req, res) => {
try {
//console.log("Solicitud recibida en la ruta '/foros/create'");

const { activitat_code } = req.body;

//const posts = [];

const docRef = await db.collection('foros').add({
'activitat_code': activitat_code,
//'posts': posts
});

res.status(201).send({ message: "Foro creado exitosamente", id: docRef.id });
}
catch (error){
//console.error("Error al crear el foro:", error);
res.status(500).send("Error interno del servidor");
}
});

//get els posts d'un foro
router.get('/:foroId/posts', async (req, res) => {
try {
const foroId = req.params.foroId;
Expand All @@ -67,7 +60,6 @@ router.get('/:foroId/posts', async (req, res) => {
const snapshot = await postsRef.get();

if (snapshot.empty) {
//console.log('No hay posts encontrados para el foro con el ID:', foroId);
res.status(404).send('No hay posts encontrados para el foro');
return;
}
Expand All @@ -79,19 +71,18 @@ router.get('/:foroId/posts', async (req, res) => {

res.status(200).json(posts);
} catch (error) {
//console.error('Error al obtener los posts del foro:', error);
res.status(500).send('Error interno del servidor');
}
});

//publica un post
// Ruta para agregar un nuevo post a un foro existente
router.post('/:foroId/posts', async (req, res) => {
//console.log("intenta crear un post")
router.post('/:foroId/posts', checkUserAndFetchData, async (req, res) => {
try {
const { username, mensaje, fecha, numero_likes } = req.body;
const { mensaje, fecha, numero_likes } = req.body;
const foroId = req.params.foroId;

const username = req.userDocument.data().username;

// Verificar si el foro existe
const foroRef = db.collection('foros').doc(foroId);
const foroSnapshot = await foroRef.get();
Expand All @@ -111,13 +102,12 @@ router.post('/:foroId/posts', async (req, res) => {

res.status(201).send("Post agregado exitosamente al foro");
} catch (error) {
//console.error("Error al agregar post al foro:", error);
res.status(500).send("Error interno del servidor");
}
});

//elimina un post
router.delete('/:foroId/posts/:postId', async(req, res) => {
router.delete('/:foroId/posts/:postId', checkUserAndFetchData, async(req, res) => {
try {
const foroId = req.params.foroId;
const postId = req.params.postId;
Expand All @@ -130,24 +120,38 @@ router.delete('/:foroId/posts/:postId', async(req, res) => {
res.status(404).send("Foro no encontrado");
return;
}

await foroRef.collection('posts').doc(postId).delete();

res.status(200).send('OK');

const username = req.userDocument.data().username;

const postSnapshot = await foroRef.collection('posts').doc(postId).get();

if (!postSnapshot.exists) {
res.status(404).send("Post no encontrado");
return;
}

const postUsername = postSnapshot.data().username;

if(username == postUsername) {
await foroRef.collection('posts').doc(postId).delete();
res.status(200).send('OK');
}
else res.status(301).send('Not creator of the post');
}
catch (error) {
res.send(error);
}
});

//crea una reply
router.post('/:foroId/posts/:postId/reply', async (req, res) => {
//console.log("intenta crear un post")
router.post('/:foroId/posts/:postId/reply', checkUserAndFetchData, async (req, res) => {
try {
const { username, mensaje, fecha, numero_likes } = req.body;
const { mensaje, fecha, numero_likes } = req.body;
const foroId = req.params.foroId;
const postId = req.params.postId;

const username = req.userDocument.data().username;

// Verificar si el foro existe
const foroRef = db.collection('foros').doc(foroId);
const foroSnapshot = await foroRef.get();
Expand Down Expand Up @@ -176,7 +180,6 @@ router.post('/:foroId/posts/:postId/reply', async (req, res) => {

res.status(201).send("Reply agregada exitosamente al foro");
} catch (error) {
//console.error("Error al agregar reply al post:", error);
res.status(500).send("Error interno del servidor");
}
});
Expand All @@ -192,7 +195,6 @@ router.get('/:foroId/posts/:postId/reply', async (req, res) => {
const snapshot = await postsRef.get();

if (snapshot.empty) {
//console.log('No hay replies encontrados para el post con el ID:', postId);
res.status(404).send('No hay replies encontrados para el post');
return;
}
Expand All @@ -204,13 +206,12 @@ router.get('/:foroId/posts/:postId/reply', async (req, res) => {

res.status(200).json(posts);
} catch (error) {
//console.error('Error al obtener las replies del foro:', error);
res.status(500).send('Error interno del servidor');
}
});

//elimina reply
router.delete('/:foroId/posts/:postId/reply/:replyId', async(req, res) => {
router.delete('/:foroId/posts/:postId/reply/:replyId', checkUserAndFetchData, async(req, res) => {
try {
const foroId = req.params.foroId;
const postId = req.params.postId;
Expand All @@ -221,14 +222,26 @@ router.delete('/:foroId/posts/:postId/reply/:replyId', async(req, res) => {
const postSnapshot = await postRef.get();

if (!postSnapshot.exists) {
//console.log('No hay replies encontrados para el post con el ID:', postId);
res.status(404).send('No hay replies encontrados para el post');
return;
}

await postRef.collection('reply').doc(replyId).delete();

res.status(200).send('OK');

const username = req.userDocument.data().username;

const replySnapshot = await postRef.collection('reply').doc(replyId).get();

if (!replySnapshot.exists) {
res.status(404).send("Reply no encontrada");
return;
}

const replyUsername = replySnapshot.data().username;

if(username == replyUsername) {
await postRef.collection('reply').doc(replyId).delete();
res.status(200).send('OK');
}
else res.status(301).send('Not creator of the post');
}
catch (error) {
res.status(500).send('Error interno del servidor');
Expand Down
2 changes: 1 addition & 1 deletion back_api/server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const app = require('./app');
require('dotenv').config();

const PORT = 8080//process.env.PORT;
const PORT = 8080 || process.env.PORT;

app.listen(PORT, async () => {
console.log(`Server is working on PORT ${PORT}`);
Expand Down

0 comments on commit 308550a

Please sign in to comment.