appointments.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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, isUser} = 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. // TODO check if a registered user accesses this / move the endpoint
  51. if (isDueDatePassed(appointment["dueDate"]) && !isUser) {
  52. return res.status(410).json({ message: 'appointment registration is closed' });
  53. } else {
  54. res.json(appointment);
  55. }
  56. }
  57. })
  58. .catch(err => {
  59. res.status(404).json({'message': "Appointment not found"});
  60. });
  61. });
  62. export { router };