Skip to content

Commit

Permalink
modified users and events services and models to add relational data b…
Browse files Browse the repository at this point in the history
  • Loading branch information
itsmePo committed Dec 20, 2024
1 parent 023d1df commit 0563c66
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 34 deletions.
Original file line number Diff line number Diff line change
@@ -1,19 +1,49 @@
import express from "express";
import User from "../models/users.js";
import Event from "../models/events.js";
import { createEvent, deleteEventById, getEventById, getEvents, updateEventById } from "../services/eventService.js"; // Importa funciones del controlador

const router = express.Router();

// Crear un evento
router.post("/", async (req, res) => {
try {
const { eventName, startDateTime, duration, color, user } = req.body;
const event = { eventName, startDateTime, duration, color, user };
await createEvent(event);
res.status(200).json({ message: 'Evento creado correctamente' });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
router.post('/create', async (req, res) => {
try {
console.log("Cuerpo completo recibido:", req.body);

const { eventName, startDateTime, duration, color, userId } = req.body; // Captura el ID del usuario desde el cuerpo de la solicitud

console.log("userId Recibido:", userId);
// Verifica que el usuario exista
const user = await User.findById(userId);

console.log("Usuario encontrado", user);

if (!user) {
return res.status(404).json({ error: 'Usuario no encontrado' });
}

// Crear el evento
const event = new Event({
eventName,
startDateTime,
duration,
color,
user: user._id, // Asocia el evento al usuario
});


const savedEvent = await event.save(); // Guarda el evento en la base de datos
user.events.push(savedEvent._id);
await user.save(); // Guarda los cambios en el usuario en la base de datos

res.status(201).json({ message: 'Evento creado correctamente', event });
} catch (error) {

console.error("Error al crear el evento:", error.message);

res.status(500).json({ error: error.message });
}
});


// Obtener todos los eventos
router.get("/", async (req, res) => {
Expand Down
2 changes: 1 addition & 1 deletion staff/borja-garcia/project/appProjectApi/models/events.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const mongoose = require('mongoose');
import mongoose from 'mongoose';

// Crear un esquema para el evento
const eventSchema = new mongoose.Schema({
Expand Down
6 changes: 6 additions & 0 deletions staff/borja-garcia/project/appProjectApi/models/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ const userSchema = new mongoose.Schema({
required: true,
minlength: 8,
},
events: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Event',
},
],
}, {
timestamps: true,
});
Expand Down
62 changes: 40 additions & 22 deletions staff/borja-garcia/project/appProjectApi/services/eventService.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,40 @@
const mongoose = require('mongoose');
const Event = require('./models/event'); // Ruta al modelo

mongoose.connect('mongodb://localhost:27017/eventsDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => console.log('Conectado a MongoDB'))
.catch(err => console.error('Error al conectar a MongoDB:', err));

// Crear un evento de ejemplo
const newEvent = new Event({
eventName: 'Reunión de equipo',
startDateTime: new Date('2024-12-20T10:00:00'), // Fecha y hora de inicio
duration: 120, // Duración en minutos
color: '#FF5733', // Color en formato HEX
});

newEvent.save()
.then(event => console.log('Evento creado:', event))
.catch(err => console.error('Error al crear el evento:', err));
import Event from "../models/events.js";
import User from "../models/users.js";
// Crear un evento
export const createEvent = async (eventObject) => {
const { userId, ...eventData } = eventObject;

// Verificar si el usuario existe
const user = await User.findById(userId);
if (!user) {
throw new Error("Usuario no encontrado");
}

// Crear y guardar el evento
const event = new Event({ ...eventData, user: userId });
const savedEvent = await event.save();

// Asociar el evento al usuario
user.events = user.events || [];
user.events.push(savedEvent._id); // Asegúrate de que el esquema del usuario tenga el campo `events`
await user.save();

return savedEvent;
};

// Obtener todos los eventos
export const getEvents = async () => {
return await Event.find();
};

export const deleteEventById = async (eventId) => {
return await Event.findByIdAndDelete(eventId);
}

export const updateEventById = async (eventId, updatedEvent) => {
return await Event.findByIdAndUpdate(eventId, updatedEvent, { new: true });
}

export const getEventById = async (eventId) => {
return await Event.findById(eventId);
}

0 comments on commit 0563c66

Please sign in to comment.