Browse Source

base backend endpoints implemented

Liontix 11 months ago
parent
commit
136b6c8138
6 changed files with 238 additions and 8 deletions
  1. 61 3
      routes/appointments.js
  2. 1 1
      routes/auth.js
  3. 110 3
      routes/members.js
  4. 36 0
      schemas/appointmentSchema.js
  5. 23 0
      schemas/bookingSchema.js
  6. 7 1
      utils.js

+ 61 - 3
routes/appointments.js

@@ -1,9 +1,67 @@
 import express from 'express';
+import Appointment from "../schemas/appointmentSchema.js";
+import Booking from "../schemas/bookingSchema.js";
+import {isDueDatePassed, isValidEmail} from "../utils.js";
 const router = express.Router();
 
-/* GET home page. */
-router.get('/', function(req, res, next) {
-    res.render('index', { title: 'Express' });
+router.post('/create', async function(req, res, next) {
+    const { appointment, email, firstname, lastname } = req.body;
+
+    const appointmentId = appointment;
+
+    if (!appointmentId || !firstname || !lastname || !email) {
+        res.status(400).json({ 'error': 'Parameters are incomplete' });
+        return;
+    }
+    if (!isValidEmail(email)) {
+        res.status(400).json({ 'error': 'Email is invalid' });
+        return;
+    }
+
+    try {
+
+        const existingAppointment = await Appointment.findOne({ _id: appointmentId });
+        if (!existingAppointment) {
+            return res.status(404).json({ message: 'appointment does not exist' });
+        }
+
+        if (isDueDatePassed(existingAppointment["dueDate"])) {
+            return res.status(401).json({ message: 'appointment registration is closed' });
+        }
+
+        const duplicateBooking = await Booking.findOne({ appointment: appointmentId, email: email })
+            .catch(err => {
+                console.log(err);
+            });
+
+        if (duplicateBooking) {
+            return res.status(404).json({ message: 'already registered' });
+        }
+
+
+        const newBooking = new Booking({ appointment, email, firstname, lastname });
+
+        newBooking.save()
+            .then(doc => res.json({ "success": true }))
+            .catch(err => res.status(500).json({ 'error': err }));
+
+    } catch (err) {
+        // Handle errors
+        console.error(err);
+        return res.status(500).json({ error: 'Internal Server Error' });
+    }
 });
 
+router.get('/', function (req, res, next) {
+    const {appointmentId} = req.query;
+    Appointment.findOne({ _id: appointmentId })
+        .then(appointment => {
+            res.json(appointment);
+        })
+        .catch(err => {
+            res.status(404).json({'message': "Appointment not found"});
+        });
+});
+
+
 export { router };

+ 1 - 1
routes/auth.js

@@ -26,7 +26,7 @@ const User = mongoose.model('User', userSchema, 'users');
 
 function generateToken(user) {
     const payload = { id: user._id };
-    return jwt.sign(payload, SECRET_KEY, {expiresIn: '1h'});
+    return jwt.sign(payload, SECRET_KEY, {expiresIn: '6h'});
 }
 
 router.post('/login', function (req, res) {

+ 110 - 3
routes/members.js

@@ -1,9 +1,116 @@
 import express from 'express';
+import passport from "passport";
+import {mongoose} from "mongoose";
+import Appointment from "../schemas/appointmentSchema.js";
+import Booking from "../schemas/bookingSchema.js";
+import AppointmentSchema from "../schemas/appointmentSchema.js";
 const router = express.Router();
 
-/* GET home page. */
-router.get('/', function(req, res, next) {
-    res.render('index', { title: 'Express' });
+
+
+router.use(passport.authenticate('jwt', { session: false }));
+
+router.use((req, res, next) => {
+    if (req.user && req.user.id) {
+        req.userId = req.user.id; // Pass user ID to req.userId
+    }
+    next();
+});
+
+
+router.post('/create', function(req, res, next) {
+    const user = req.userId;
+    const { title, description, dueDate, place, startDate, endDate } = req.body;
+
+    if (!title || title.length === 0 || !dueDate || !dueDate || !description || !startDate || !endDate || !place) {
+        res.status(400).json({ 'error': 'Empty parameter' });
+        return;
+    }
+
+    const newTask = new Appointment({ user, title, description, dueDate, place, startDate, endDate });
+
+    newTask.save()
+        .then(doc => res.json({ "success": true }))
+        .catch(err => res.status(500).json({ 'error': err }));
+
 });
 
+router.put('/modify', function (req, res, next) {
+    const user = req.userId;
+
+    const { appointmentId, title, description, dueDate, place, startDate, endDate } = req.body;
+    if (!title || !dueDate || !dueDate || !description || !startDate || !endDate || !place || !appointmentId) {
+        res.status(400).json({ 'error': 'Empty parameter' });
+        return;
+    }
+
+    console.log(appointmentId);
+    console.log(user);
+
+    Appointment.updateOne(
+        { _id: appointmentId, user: user },
+        { $set: { title, description, dueDate, place, startDate, endDate } }
+    )
+        .then(result => {
+            if (result.modifiedCount === 1) {
+                console.log("Successfully updated the document.");
+                res.json({ "success": true });
+            } else {
+                console.log("Document not updated");
+                res.status(500).json({ 'error': 'Document has not changed' });
+            }
+        })
+        .catch(err => res.status(404).json({ 'error': 'Not found' }));
+});
+
+router.delete('/delete', function (req, res, next) {
+    const user = req.userId;
+    const {appointmentId} = req.body;
+    if (!appointmentId) {
+        res.status(400).json({ 'error': 'Invalid parameter' });
+        return;
+    }
+
+    Appointment.deleteOne({ _id: appointmentId, user: user })
+        .then(result => {
+            if (result.deletedCount === 1) {
+                res.json({ 'success': true });
+            } else {
+                res.status(404).json({ 'error': 'Not found' });
+            }
+        })
+        .catch(err => res.status(500).json({ 'error': err }));
+});
+
+
+router.get('/appointments', function (req, res, next) {
+    const user = req.userId;
+    Appointment.find({ user: user })
+        .then(appointments => {
+            res.json(appointments);
+        })
+        .catch(err => {
+            res.status(404).json({'message': "Appointments not found"});
+        });
+});
+
+router.get('/bookings', function (req, res, next) {
+    const { appointmentId } = req.query;
+
+    if (!appointmentId) {
+        res.status(400).json({ 'error': 'Empty parameter' });
+        return;
+    }
+
+    Booking.find({ appointment: appointmentId })
+        .then(tasks => {
+            res.json(tasks);
+        })
+        .catch(err => {
+            res.status(404).json({'message': "Appointment not found"});
+        });
+
+});
+
+
 export { router };

+ 36 - 0
schemas/appointmentSchema.js

@@ -0,0 +1,36 @@
+import mongoose from "mongoose";
+
+
+const appointmentSchema = new mongoose.Schema({
+    user: {
+        type: String,
+        required: true
+    },
+    title: {
+        type: String,
+        required: true
+    },
+    description: {
+        type: String,
+        required: true
+    },
+    dueDate: {
+        type: Date,
+        required: true
+    },
+    place: {
+        type: String,
+        required: true
+    },
+    startDate: {
+        type: Date,
+        required: true
+    },
+    endDate: {
+        type: Date,
+        required: true
+    }
+});
+const Appointment = mongoose.model('Appointment', appointmentSchema, 'appointment');
+
+export default Appointment;

+ 23 - 0
schemas/bookingSchema.js

@@ -0,0 +1,23 @@
+import mongoose from "mongoose";
+
+const bookingSchema = new mongoose.Schema({
+    appointment: {
+        type: String,
+        required: true
+    },
+    email: {
+        type: String,
+        required: true
+    },
+    firstname: {
+        type: String,
+        required: true
+    },
+    lastname: {
+        type: String,
+        required: true
+    }
+});
+const Booking = mongoose.model('Booking', bookingSchema, 'booking');
+
+export default Booking;

+ 7 - 1
utils.js

@@ -4,4 +4,10 @@ function isValidEmail(email) {
     return emailRegex.test(email);
 }
 
-export {isValidEmail};
+function isDueDatePassed(dueDate) {
+    const now = new Date();
+    const dueDateTime = new Date(dueDate);
+    return dueDateTime < now;
+}
+
+export {isValidEmail, isDueDatePassed};