From f94ec0ba144660a956ab218dff6bb9b5c3e7564a Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Thu, 2 May 2024 01:20:56 +0100 Subject: [PATCH] implemented episode seen hook for create/update/delete --- backend/db/sequelizeHooks.js | 174 ++++++++++++++++++++++++++++ backend/routes/episodeSeenRoutes.js | 137 +++------------------- 2 files changed, 190 insertions(+), 121 deletions(-) diff --git a/backend/db/sequelizeHooks.js b/backend/db/sequelizeHooks.js index 4b8f0f3..ee6b373 100644 --- a/backend/db/sequelizeHooks.js +++ b/backend/db/sequelizeHooks.js @@ -213,3 +213,177 @@ EntrySeen.afterDestroy(async (instance, options) => { console.log(`Sequelize Hook Error: EntrySeen.afterUpdate: `, error) } }); + +// ? episode seen +// * episode-seen create +EpisodeSeen.afterCreate(async (instance, options) => { + try { + // ! updating the entry + // ? getting the entry that we just created the episode-seen for + const entry = await Entry.findByPk(instance.entry_id); + + // this will ensure that the entry is updated anyways to trigger the updatedAt property + let update = { + title: sequelize.literal('title') + }; + + // ? comparing the instance.date_seen with the entry date_first_seen & + // ? date_last_seen to check if they should be replaced + if (!entry.date_first_seen || instance.date_seen < new Date(entry.date_first_seen)) { + update.date_first_seen = instance.date_seen; + } + if (!entry.date_last_seen || instance.date_seen > new Date(entry.date_last_seen)) { + update.date_last_seen = instance.date_seen; + } + + // * updating the entry + await entry.update(update); + + // ! updating the episode + // ? getting the episode that we just created the episode-seen for + const episode = await Episode.findByPk(instance.episode_id); + + // this will ensure that the episode is updated anyways to trigger the updatedAt property + let episodeUpdate = { + name: sequelize.literal('name') + }; + + // ? comparing the instance.date_seen with the entry date_first_seen & + // ? date_last_seen to check if they should be replaced + if (!episode.date_first_seen || instance.date_seen < new Date(episode.date_first_seen)) { + episodeUpdate.date_first_seen = instance.date_seen; + } + if (!episode.date_last_seen || instance.date_seen > new Date(episode.date_last_seen)) { + episodeUpdate.date_last_seen = instance.date_seen; + } + + // * updating the episode + await episode.update(episodeUpdate); + } catch (error) { + console.log(`Sequelize Hook Error: EpisodeSeen.afterCreate: `, error) + } +}); + +// * episode-seen udpate +EpisodeSeen.afterUpdate(async (instance, options) => { + try { + // ! updating the entry + // ? getting the entry that we just created the episode-seen for + const entry = await Entry.findByPk(instance.entry_id); + + // ? getting the min & max values of the column date_seen from episode-seen + // ? for the current entry + EpisodeSeen.findAll({ + attributes: [ + [sequelize.fn('min', sequelize.col('date_seen')), 'minValue'], + [sequelize.fn('max', sequelize.col('date_seen')), 'maxValue'] + ], + where: { + entry_id: instance.entry_id + } + }).then(result => { + let update = {}; + + update.date_first_seen = result[0].dataValues.minValue; + update.date_last_seen = result[0].dataValues.maxValue; + + entry.update(update); + }).catch(err => { + console.error('Error:', err); + }); + + // ! updating the episode + // ? getting the episode that we just created the episode-seen for + const episode = await Episode.findByPk(instance.episode_id); + + // ? getting the min & max values of the column date_seen from episode-seen + // ? for the current episode + EpisodeSeen.findAll({ + attributes: [ + [sequelize.fn('min', sequelize.col('date_seen')), 'minValue'], + [sequelize.fn('max', sequelize.col('date_seen')), 'maxValue'] + ], + where: { + episode_id: instance.episode_id + } + }).then(result => { + let update = {}; + update.date_first_seen = result[0].dataValues.minValue; + update.date_last_seen = result[0].dataValues.maxValue; + episode.update(update); + }).catch(err => { + console.error('Error:', err); + }); + } catch (error) { + console.log(`Sequelize Hook Error: EpisodeSeen.afterUpdate: `, error) + } +}); + +// * episode-seen delete +EpisodeSeen.afterDestroy(async (instance, options) => { + try { + // ! updating the entry + // ? getting the entry that we just created the entry-seen for + const entry = await Entry.findByPk(instance.entry_id); + + // ? getting the list of entry-seen for the current entry, sorted by date_seen + // ? then asigning the first one in the array to: date_first_seen + // ? and the last one to: date_last_seen + const episodeSeens = await EpisodeSeen.findAll({ + where: { + entry_id: instance.entry_id + }, + order: [ + ['date_seen', 'ASC'] + ] + }); + + let update = {}; + + // ? if the deleted entry-seen was the only one available for the current entry + // ? then set date_first_seen & date_last_seen values to `null` + if (episodeSeens.length == 0) { + update.date_first_seen = null; + update.date_last_seen = null; + } else { + update.date_first_seen = episodeSeens[0].date_seen; + update.date_last_seen = episodeSeens[episodeSeens.length - 1].date_seen; + } + + // * updating the entry + await entry.update(update); + + // ! updating the episode + // ? getting the entry that we just created the episode-seen for + const episode = await Episode.findByPk(instance.episode_id); + + // ? getting the list of episode-seen for the current episode, sorted by date_seen + // ? then asigning the first one in the array to: date_first_seen + // ? and the last one to: date_last_seen + const episodeSeens2 = await EpisodeSeen.findAll({ + where: { + episode_id: instance.episode_id + }, + order: [ + ['date_seen', 'ASC'] + ] + }); + + let episodeUpdate = {}; + + // ? if the deleted episode-seen was the only one available for the current episode + // ? then set date_first_seen & date_last_seen values to `null` + if (episodeSeens2.length == 0) { + episodeUpdate.date_first_seen = null; + episodeUpdate.date_last_seen = null; + } else { + episodeUpdate.date_first_seen = episodeSeens2[0].date_seen; + episodeUpdate.date_last_seen = episodeSeens2[episodeSeens2.length - 1].date_seen; + } + + // * updating the episode + await episode.update(episodeUpdate); + } catch (error) { + console.log(`Sequelize Hook Error: EpisodeSeen.afterUpdate: `, error) + } +}); \ No newline at end of file diff --git a/backend/routes/episodeSeenRoutes.js b/backend/routes/episodeSeenRoutes.js index 11a7ab5..43b4884 100644 --- a/backend/routes/episodeSeenRoutes.js +++ b/backend/routes/episodeSeenRoutes.js @@ -2,6 +2,7 @@ const express = require('express'); const Episode = require('../models/Episode'); const EpisodeSeen = require('../models/EpisodeSeen'); const Season = require('../models/Season'); +const Entry = require('../models/Entry'); const episodeSeenRouter = express.Router(); // ! /episode-seen @@ -10,40 +11,13 @@ episodeSeenRouter.post('/', async (req, res) => { try { const { entry_id, episode_id, date_seen, seen_with } = req.body; - // Fetch the Entry based on entry_id + const entry = await Entry.findByPk(entry_id); + if (!entry) + return res.status(404).json({ error: "Entry not found" }); + const episode = await Episode.findByPk(episode_id); - if (!episode) { + if (!episode) return res.status(404).json({ error: "Episode not found" }); - } - - const episodeSeens = await EpisodeSeen.findAll({ - where: { - episode_id: episode_id - }, - order: [ - ['date_seen', 'DESC'] - ] - }); - - let update = {}; - const dateSeen = new Date(date_seen); - - if (episodeSeens.length == 0) { // ? case of first episodeSeen - update.date_first_seen = date_seen; - update.date_last_seen = date_seen; - } else { // ? case of 2nd+ episodeSeen - if (!episode.date_first_seen || dateSeen < new Date(episode.date_first_seen)) { - update.date_first_seen = date_seen; - } - if (!episode.date_last_seen || dateSeen > new Date(episode.date_last_seen)) { - update.date_last_seen = date_seen; - } - } - - // Update the Episode with new first or last seen dates - if (Object.keys(update).length > 0) { - await episode.update(update); - } // Create a new EpisodeSeen record const newEpisodeSeen = await EpisodeSeen.create({ entry_id, episode_id, date_seen, seen_with }); @@ -125,48 +99,15 @@ episodeSeenRouter.get('/by-entry/:entryId', async (req, res) => { episodeSeenRouter.put('/:id', async (req, res) => { try { const { date_seen, seen_with, episode_id } = req.body; - const updated = await EpisodeSeen.update({ date_seen, seen_with }, { where: { id: req.params.id } }); - // * episode update - // Fetch the Entry based on entry_id - const episode = await Episode.findByPk(episode_id); - if (!episode) { - return res.status(404).json({ error: "Episode not found" }); - } + const episodeSeen = await EpisodeSeen.findByPk(req.params.id) + if (!episodeSeen) + return res.status(404).json({ message: 'Episode seen record not found.' }); - const episodeSeens = await EpisodeSeen.findAll({ - where: { - episode_id: episode_id - }, - order: [ - ['date_seen', 'DESC'] - ] - }); + const updated = await episodeSeen.update({ date_seen, seen_with }); - let update = {}; - const dateSeen = new Date(date_seen); - - if (episodeSeens.length == 0) { // ? case of first episodeSeen - update.date_first_seen = date_seen; - update.date_last_seen = date_seen; - } else { // ? case of 2nd+ episodeSeen - if (!episode.date_first_seen || dateSeen < new Date(episode.date_first_seen)) { - update.date_first_seen = date_seen; - } - if (!episode.date_last_seen || dateSeen > new Date(episode.date_last_seen)) { - update.date_last_seen = date_seen; - } - } - - // Update the Episode with new first or last seen dates - if (Object.keys(update).length > 0) { - await episode.update(update); - } - // + end episode update - - if (updated[0] > 0) { - const updatedEpisodeSeen = await EpisodeSeen.findByPk(req.params.id); - res.status(200).json(updatedEpisodeSeen); + if (updated) { + res.status(200).json(updated); } else { res.status(404).json({ message: 'Episode seen record not found.' }); } @@ -178,62 +119,16 @@ episodeSeenRouter.put('/:id', async (req, res) => { // * DELETE - EPISODE SEEN episodeSeenRouter.delete('/:id', async (req, res) => { try { - // getting the episode seen object + // ? getting the episode seen object const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id); if (!oldEpisodeSeen) res.status(404).json({ message: 'Episode seen record not found.' }); + // ?deleting the episode seen + const deleted = await oldEpisodeSeen.destroy(); - // * episode update - const episode = await Episode.findByPk(oldEpisodeSeen.episode_id); - if (!episode) { - return res.status(404).json({ message: "Episode not found" }); - } - - // deleting the episode seen - const deleted = await EpisodeSeen.destroy({ where: { id: req.params.id } }); - - const episodeSeens = await EpisodeSeen.findAll({ - where: { - episode_id: episode.id - }, - order: [ - ['date_seen', 'DESC'] - ] - }); - - let update = {}; - - if (episodeSeens.length == 0) { // ? case of 0 episodeSeen for the episode - update.date_first_seen = null; - update.date_last_seen = null; - } else { // ? case of 1+ episodeSeen for the episode - for (let i = 0; i < episodeSeens.length; i++) { - if (i == 0) { - update.date_first_seen = episodeSeens[i].date_seen; - update.date_last_seen = episodeSeens[i].date_seen; - } else { - if (episodeSeens[i].date_seen < update.date_first_seen) { - update.date_first_seen = episodeSeens[i].date_seen; - } - if (episodeSeens[i].date_seen > update.date_last_seen) { - update.date_last_seen = episodeSeens[i].date_seen; - } - } - } - } - - // Update the Episode with new first or last seen dates - if (Object.keys(update).length > 0) { - await episode.update(update); - } - // + end episode update - - if (deleted) { + if (deleted) res.status(204).send(); - } else { - res.status(404).json({ message: 'Episode seen record not found.' }); - } } catch (error) { res.status(500).json({ error: error.message }); console.log(error)