appointments.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import express from 'express';
  2. import Appointment from "../schemas/appointmentSchema.js";
  3. import Booking from "../schemas/bookingSchema.js";
  4. import {isDueDatePassed, isValidEmail} from "../utils.js";
  5. import {app} from "../app.js";
  6. const router = express.Router();
  7. router.post('/create', async function(req, res, next) {
  8. const { appointment, email, firstname, lastname } = req.body;
  9. const appointmentId = appointment;
  10. if (!appointmentId || !firstname || !lastname || !email) {
  11. res.status(400).json({ 'message': 'Parameters are incomplete' });
  12. return;
  13. }
  14. if (!isValidEmail(email)) {
  15. res.status(400).json({ 'message': 'Email is invalid' });
  16. return;
  17. }
  18. try {
  19. const existingAppointment = await Appointment.findOne({ _id: appointmentId });
  20. if (!existingAppointment) {
  21. return res.status(404).json({ message: 'appointment does not exist' });
  22. }
  23. if (isDueDatePassed(existingAppointment["dueDate"])) {
  24. return res.status(401).json({ message: 'appointment registration is closed' });
  25. }
  26. const duplicateBooking = await Booking.findOne({ appointment: appointmentId, email: email })
  27. .catch(err => {
  28. console.log(err);
  29. });
  30. if (duplicateBooking) {
  31. return res.status(404).json({ message: 'already registered' });
  32. }
  33. const newBooking = new Booking({ appointment, email, firstname, lastname });
  34. newBooking.save()
  35. .then(doc => res.json({ "success": true }))
  36. .catch(err => res.status(500).json({ 'error': err }));
  37. } catch (err) {
  38. // Handle errors
  39. console.error(err);
  40. return res.status(500).json({ error: 'Internal Server Error' });
  41. }
  42. });
  43. router.get('/', function (req, res, next) {
  44. const {appointmentId} = req.query;
  45. Appointment.findOne({ _id: appointmentId })
  46. .then(appointment => {
  47. if (appointment === null) {
  48. res.status(404).json({'message': "Appointment not found"});
  49. } else {
  50. if (isDueDatePassed(appointment["dueDate"])) {
  51. return res.status(410).json({ message: 'appointment registration is closed' });
  52. } else {
  53. res.json(appointment);
  54. }
  55. }
  56. })
  57. .catch(err => {
  58. res.status(404).json({'message': "Appointment not found"});
  59. });
  60. });
  61. export { router };