import { Request, Response } from "express"; import Boat from "../db/models/Boat"; import Sport from "../db/models/Sport"; const createSportController = async (req: Request, res: Response) => { try { const { id, name, color } = req.body; const newSport = await Sport.create({ id, name, color }); return res.status(201).json({ success: true, result: { id: newSport.id, name: newSport.name, color: newSport.color, }, }); } catch (error) { return res.status(500).json({ success: false, error: "serverError" }); } }; const showAllSports = async (req: Request, res: Response) => { try { const allSports = await Sport.findAll(); return res.status(200).send({ success: true, result: allSports.map((Sport) => { return { id: Sport.id, name: Sport.name, color: Sport.color }; }), }); } catch (error) { return res.status(500).json({ success: false, error: "serverError" }); } }; const deleteSportById = async (req: Request, res: Response) => { try { const sportToDelete = await Sport.destroy({ where: { id: req.params.id, }, }); if (!sportToDelete) { return res .status(404) .json({ success: false, error: "sportIdDoesNotExist" }); } return res.status(200).json({ success: true }); } catch (error) { return res.status(500).json({ success: false, error: "serverError" }); } }; const updateSportById = async (req: Request, res: Response) => { try { const input = req.body; //return 200 with empty response if no data was given if (Object.keys(input).length === 0) { return res .status(200) .json({ success: true, result: {}, message: "noInputFound" }); } //check if sport can be found using givenId if (!await Sport.findByPk(req.params.id)) { return res.status(404).json({ success: false, error: "sportIdNotFound" }); } const updatedSport = await Sport.update(input, { where: { id: req.params.id, }, returning: true, }); //return after updating const sportDataAfterUpdate = updatedSport[1][0]; return res.status(200).json({ success: true, result: { id: sportDataAfterUpdate.id, name: sportDataAfterUpdate.name, color: sportDataAfterUpdate.color, }, }); } catch (error) { return res.status(500).json({ success: false, error: "serverError" }); } }; const showSportByBoatId = async (req: Request, res: Response) => { try { const givenId = req.params.id; const boat = await Boat.findByPk(givenId); if (boat) { return res.status(200).json({ success: true, result: boat }); } return res.status(404).json({ success: false, error: "boatIdNotFound" }); } catch (error) { return res.status(500).json({ success: false, error: "serverError" }); } }; const sportControllers = { createSportController, showAllSports, deleteSportById, updateSportById, showSportByBoatId, }; export default sportControllers;