appointments.js 2.8 KB

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