const createError = require('http-errors'); const { Fish, sequelize } = require('../models'); exports.addFish = (opts) => { return async function (req, res, next) { try { const { fish } = req.body; const result = await sequelize.transaction(async (t) => { const newFish = await Fish.create({ name: fish.name, color: fish.color, length: fish.length, speed: fish.speed, }); return { newFish } }); res.status(200).json({ msg: `Added fish to the database.` }); } catch (error) { return next(createError.InternalServerError(error)); } } } exports.updateFish = (opts) => { return async function (req, res, next) { try { const { id: fishId } = req.params; const { fish } = req.body; const result = await sequelize.transaction(async (t) => { const updatedFish = Fish.update({ name: fish.name, color: fish.color, length: fish.length, speed: fish.speed, }, { where: { id: fishId } }); return { updatedFish } }); res.status(200).json({ msg: `Updated fish.` }); } catch (error) { return next(createError.InternalServerError(error)); } } } exports.deleteFish = (opts) => { return async function (req, res, next) { try { const { id: fishId } = req.params; const result = await sequelize.transaction(async (t) => { const deletedFish = await Fish.destroy({ where: { id: fishId } }); return { deletedFish }; }); return res.status(200).json({ msg: "Deleted fish." }); } catch (error) { return next(createError.InternalServerError(error)); } } } exports.getAllFish = (opts) => { return async function (req, res, next) { try { const fishes = await Fish.findAll(); if (!fishes) { return next(createError.NotFound("No fishes in the database.")); } return res.status(200).json(fishes); } catch (error) { return next(createError.InternalServerError(error)); } } } exports.getFish = (opts) => { return async function (req, res, next) { try { const { id: fishId } = req.params; const fish = await Fish.findOne({ where: { id: fishId } }); if (!fish) { return next(createError.NotFound()); } return res.status(200).json(fish); } catch (error) { return next(createError.InternalServerError(error)); } } }