const express = require('express'); const router = express.Router(); const { v4: uuidv4 } = require('uuid'); const { authenticate } = require('../../middlewares/authenticate'); const { validateParticipantID, } = require('../../middlewares/validateParticipantID'); const Participant = require('../models/participantModel'); router.post('/', authenticate, async (req, res) => { id = uuidv4(); const data = { ...req.body, id }; try { const [participant] = await Participant.addParticipant(data); res.status(201).json(participant); } catch (error) { res.status(500).json({ message: 'Failed to add new participant.', error, }); } }); router.put('/:id', authenticate, validateParticipantID, async (req, res) => { const data = { ...req.body }; const { id } = req.params; try { const participant = await Participant.updateParticipant(data, id); res.status(200).json(...participant); } catch (error) { res.status(500).json({ message: 'Failed to update participant.', error, }); } }); router.delete('/:id', authenticate, validateParticipantID, async (req, res) => { const { id } = req.params; try { const participant = await Participant.deleteParticipant(id); res.status(200).json({ message: `Participant with id ${id} successfully deleted.`, }); } catch (error) { res.status(500).json({ message: `Failed to delete participant with id ${id}.`, error, }); } }); router.get('/:id', authenticate, async (req, res) => { const { id } = req.params; try { const participant = await Participant.getParticipantById(id); if (typeof participant == 'undefined') { res.status(404).json({ message: `Participant with id ${id} doesn't exist.`, }); } else { res.status(200).json(participant); } } catch (error) { res.status(500).json({ message: `Failed to get participant with id ${id}.`, error, }); } }); module.exports = router;