appointments.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * Import required dependencies.
  3. */
  4. import express from 'express';
  5. import Appointment from "../schemas/appointmentSchema.js";
  6. import Booking from "../schemas/bookingSchema.js";
  7. import {isDueDatePassed, isValidEmail} from "../utils.js";
  8. /**
  9. * Create an Express router for handling appointment-related routes.
  10. */
  11. const router = express.Router();
  12. /**
  13. * Create a new appointment and associate it with a booking.
  14. */
  15. router.post('/create', async function(req, res, next) {
  16. const { appointment, email, firstname, lastname } = req.body;
  17. const appointmentId = appointment;
  18. if (!appointmentId || !firstname || !lastname || !email) {
  19. res.status(400).json({ 'message': 'Parameters are incomplete' });
  20. return;
  21. }
  22. if (!isValidEmail(email)) {
  23. res.status(400).json({ 'message': 'Email is invalid' });
  24. return;
  25. }
  26. try {
  27. const existingAppointment = await Appointment.findOne({ _id: appointmentId });
  28. if (!existingAppointment) {
  29. return res.status(404).json({ message: 'appointment does not exist' });
  30. }
  31. if (isDueDatePassed(existingAppointment["dueDate"])) {
  32. return res.status(401).json({ message: 'appointment registration is closed' });
  33. }
  34. const duplicateBooking = await Booking.findOne({ appointment: appointmentId, email: email })
  35. .catch(err => {
  36. console.log(err);
  37. });
  38. if (duplicateBooking) {
  39. return res.status(404).json({ message: 'already registered' });
  40. }
  41. const newBooking = new Booking({ appointment, email, firstname, lastname });
  42. newBooking.save()
  43. .then(doc => res.json({ "success": true }))
  44. .catch(err => res.status(500).json({ 'error': err }));
  45. } catch (err) {
  46. // Handle errors
  47. console.error(err);
  48. return res.status(500).json({ error: 'Internal Server Error' });
  49. }
  50. });
  51. /**
  52. * Retrieve an appointment by ID.
  53. */
  54. router.get('/', function (req, res, next) {
  55. const {appointmentId, isUser} = req.query;
  56. Appointment.findOne({ _id: appointmentId })
  57. .then(appointment => {
  58. if (appointment === null) {
  59. res.status(404).json({'message': "Appointment not found"});
  60. } else {
  61. // Check if a registered user accesses this endpoint
  62. if (isDueDatePassed(appointment["dueDate"]) && !isUser) {
  63. return res.status(410).json({ message: 'appointment registration is closed' });
  64. } else {
  65. res.json(appointment);
  66. }
  67. }
  68. })
  69. .catch(err => {
  70. res.status(404).json({'message': "Appointment not found"});
  71. });
  72. });
  73. export { router };