implemented episode seen hook for create/update/delete

This commit is contained in:
X4Lo committed 2024-05-02 01:20:56 +01:00
1 parent a5b66b4136
commit f94ec0ba14
2 files changed
+190 -121

No files matched your search

+174
View File
@@ -213,3 +213,177 @@ EntrySeen.afterDestroy(async (instance, options) => {
console.log(`Sequelize Hook Error: EntrySeen.afterUpdate: `, error) 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)
}
});
+16 -121
View File
@@ -2,6 +2,7 @@ const express = require('express');
const Episode = require('../models/Episode'); const Episode = require('../models/Episode');
const EpisodeSeen = require('../models/EpisodeSeen'); const EpisodeSeen = require('../models/EpisodeSeen');
const Season = require('../models/Season'); const Season = require('../models/Season');
const Entry = require('../models/Entry');
const episodeSeenRouter = express.Router(); const episodeSeenRouter = express.Router();
// ! /episode-seen // ! /episode-seen
@@ -10,40 +11,13 @@ episodeSeenRouter.post('/', async (req, res) => {
try { try {
const { entry_id, episode_id, date_seen, seen_with } = req.body; 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); const episode = await Episode.findByPk(episode_id);
if (!episode) { if (!episode)
return res.status(404).json({ error: "Episode not found" }); 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 // Create a new EpisodeSeen record
const newEpisodeSeen = await EpisodeSeen.create({ entry_id, episode_id, date_seen, seen_with }); 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) => { episodeSeenRouter.put('/:id', async (req, res) => {
try { try {
const { date_seen, seen_with, episode_id } = req.body; 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 const episodeSeen = await EpisodeSeen.findByPk(req.params.id)
// Fetch the Entry based on entry_id if (!episodeSeen)
const episode = await Episode.findByPk(episode_id); return res.status(404).json({ message: 'Episode seen record not found.' });
if (!episode) {
return res.status(404).json({ error: "Episode not found" });
}
const episodeSeens = await EpisodeSeen.findAll({ const updated = await episodeSeen.update({ date_seen, seen_with });
where: {
episode_id: episode_id
},
order: [
['date_seen', 'DESC']
]
});
let update = {}; if (updated) {
const dateSeen = new Date(date_seen); res.status(200).json(updated);
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);
} else { } else {
res.status(404).json({ message: 'Episode seen record not found.' }); res.status(404).json({ message: 'Episode seen record not found.' });
} }
@@ -178,62 +119,16 @@ episodeSeenRouter.put('/:id', async (req, res) => {
// * DELETE - EPISODE SEEN // * DELETE - EPISODE SEEN
episodeSeenRouter.delete('/:id', async (req, res) => { episodeSeenRouter.delete('/:id', async (req, res) => {
try { try {
// getting the episode seen object // ? getting the episode seen object
const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id); const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id);
if (!oldEpisodeSeen) if (!oldEpisodeSeen)
res.status(404).json({ message: 'Episode seen record not found.' }); res.status(404).json({ message: 'Episode seen record not found.' });
// ?deleting the episode seen
const deleted = await oldEpisodeSeen.destroy();
// * episode update if (deleted)
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) {
res.status(204).send(); res.status(204).send();
} else {
res.status(404).json({ message: 'Episode seen record not found.' });
}
} catch (error) { } catch (error) {
res.status(500).json({ error: error.message }); res.status(500).json({ error: error.message });
console.log(error) console.log(error)