appointments.js 2.1 KB

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