288 lines
9.3 KiB
JavaScript
288 lines
9.3 KiB
JavaScript
const express = require('express');
|
|
const UserCollection = require('../models/UserCollection');
|
|
const UserCollectionEntry = require('../models/UserCollectionEntry');
|
|
const Entry = require('../models/Entry');
|
|
const EntryId = require('../models/EntryId');
|
|
const EntryRating = require('../models/EntryRating');
|
|
const Season = require('../models/Season');
|
|
const Genre = require('../models/Genre');
|
|
const Media = require('../models/Media');
|
|
|
|
const { Sequelize } = require('sequelize');
|
|
const router = express.Router();
|
|
const multer = require('multer');
|
|
const { v4: uuidv4 } = require('uuid');
|
|
const path = require('path');
|
|
const { getMediaFolder, generatePreview } = require('../services/mediaService');
|
|
|
|
// ! /user-collections
|
|
// * GET - ALL UserCollections
|
|
router.get('/', async (req, res) => {
|
|
let userCollections; // Declare outside to broaden scope, albeit unnecessary in your given context
|
|
try {
|
|
userCollections = await UserCollection.findAll({
|
|
include: [
|
|
{
|
|
model: Entry, as: 'entries',
|
|
include: { model: Media, as: 'medias' }
|
|
},
|
|
],
|
|
order: [['name', 'ASC']]
|
|
});
|
|
res.status(200).json(userCollections);
|
|
} catch (error) {
|
|
console.error("Error fetching UserCollections:", error); // More detailed error logging
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// * GET - userCollection BY ID
|
|
router.get('/:id', async (req, res) => {
|
|
try {
|
|
const userCollection = await UserCollection.findByPk(req.params.id, {
|
|
include: [{
|
|
model: Entry,
|
|
as: 'entries',
|
|
include: [
|
|
{ model: EntryId, as: 'entryId' },
|
|
{ model: EntryRating, as: 'entryRating' },
|
|
{ model: Season, as: 'seasons' },
|
|
{ model: Media, as: 'medias' },
|
|
{ model: Genre, as: 'genres' },
|
|
],
|
|
through: {
|
|
model: UserCollectionEntry,
|
|
attributes: ['order'], // attributes (to include) from the join model
|
|
},
|
|
}],
|
|
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
|
|
});
|
|
|
|
if (userCollection) {
|
|
const collectionData = userCollection.get({ plain: true });
|
|
for (let i = 0; i < collectionData.entries.length; i++) {
|
|
const genres = collectionData.entries[i].genres.map(genre => genre.name);
|
|
collectionData.entries[i].genres = genres
|
|
}
|
|
|
|
res.status(200).json(collectionData);
|
|
} else {
|
|
res.status(404).json({ message: 'UserCollection not found' });
|
|
}
|
|
} catch (error) {
|
|
console.log(`Error getting collection info: `, error)
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// * POST - CREATE UserCollection
|
|
router.post('/', async (req, res) => {
|
|
try {
|
|
const { name, description, userRating, posterPath } = req.body;
|
|
const isUserCollection = true;
|
|
const newUserCollection = await UserCollection.create({ name, description, userRating, posterPath, isUserCollection });
|
|
res.status(201).json(newUserCollection);
|
|
} catch (error) {
|
|
res.status(400).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
const storage = multer.diskStorage({
|
|
destination: function (req, file, cb) {
|
|
cb(null, path.join(getMediaFolder(), 'images', 'collections', 'posters'))
|
|
},
|
|
filename: function (req, file, cb) {
|
|
const uniqueFilename = uuidv4();
|
|
const extension = file.originalname.split('.').pop();
|
|
cb(null, `${uniqueFilename}.${extension}`);
|
|
}
|
|
});
|
|
|
|
const upload = multer({ storage: storage });
|
|
// * PUT - UPDATE A UserCollection
|
|
router.put('/:id', upload.single('poster'), async (req, res) => {
|
|
try {
|
|
const userCollectionId = req.params.id;
|
|
const { name, description, userRating, is_poster_link } = req.body;
|
|
|
|
let posterPath = req.file ? req.file.filename : undefined;
|
|
|
|
const updateData = {
|
|
name,
|
|
description,
|
|
userRating: parseInt(userRating, 10),
|
|
isLocal: false,
|
|
|
|
};
|
|
|
|
if (posterPath) {
|
|
updateData.posterPath = posterPath;
|
|
updateData.isLocal = true;
|
|
|
|
// ? generating preview
|
|
const fileNameWithoutExt = req.file.filename.split('.')[0];
|
|
const originalPath = req.file.path;
|
|
|
|
let previewWidth = 342; // ? poster preview width
|
|
const previewPath = path.join(req.file.destination, `${fileNameWithoutExt}_preview.jpg`);
|
|
generatePreview(originalPath, previewPath, previewWidth);
|
|
}
|
|
|
|
const updated = await UserCollection.update(updateData, {
|
|
where: { id: userCollectionId }
|
|
});
|
|
|
|
if (!updated[0]) {
|
|
return res.status(404).json({ message: 'UserCollection not found' });
|
|
}
|
|
|
|
if (updated) {
|
|
const updatedUserCollection = await UserCollection.findByPk(userCollectionId, {
|
|
include: [{
|
|
model: Entry,
|
|
as: 'entries',
|
|
include: [
|
|
{ model: EntryId, as: 'entryId' },
|
|
{ model: EntryRating, as: 'entryRating' },
|
|
{ model: Season, as: 'seasons' },
|
|
{ model: Media, as: 'medias' },
|
|
{ model: Genre, as: 'genres' },
|
|
],
|
|
through: {
|
|
model: UserCollectionEntry,
|
|
attributes: ['order'], // attributes (to include) from the join model
|
|
},
|
|
}],
|
|
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
|
|
});
|
|
|
|
res.status(200).json(updatedUserCollection);
|
|
} else {
|
|
res.status(404).json({ message: 'UserCollection not found' });
|
|
}
|
|
} catch (error) {
|
|
console.log(`UserCollection update (put) error: `, error)
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// * DELETE - A UserCollection
|
|
router.delete('/:id', async (req, res) => {
|
|
try {
|
|
const deleted = await UserCollection.destroy({ where: { id: req.params.id } });
|
|
if (deleted) {
|
|
res.status(204).send();
|
|
} else {
|
|
res.status(404).json({ message: 'UserCollection not found' });
|
|
}
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// * POST - ADD ENTRY TO A UserCollection
|
|
router.post('/:userCollectionId/entries/:entryId', async (req, res) => {
|
|
try {
|
|
const { userCollectionId, entryId } = req.params;
|
|
|
|
const newUserCollectionEntry = await UserCollectionEntry.create({
|
|
user_collection_id: userCollectionId,
|
|
entry_id: entryId
|
|
});
|
|
|
|
// ? set a default poster if none exists
|
|
const userCollection = await UserCollection.findByPk(userCollectionId);
|
|
if (!userCollection.poster_path || userCollection.poster_path.trim() === '') {
|
|
const entry = await Entry.findByPk(entryId);
|
|
userCollection.poster_path = entry.poster_path;
|
|
await userCollection.save();
|
|
}
|
|
|
|
res.status(201).json(newUserCollectionEntry);
|
|
} catch (error) {
|
|
console.log(error)
|
|
res.status(400).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// * PATCH - UPDATE ENTRY ORDER IN UserCollection
|
|
router.patch('/:userCollectionId/entries/:entryId', async (req, res) => {
|
|
try {
|
|
const { userCollectionId, entryId } = req.params;
|
|
const { newOrder } = req.body;
|
|
|
|
// ? getting the collectionEntry
|
|
const collectionEntry = await UserCollectionEntry.findOne({
|
|
where: {
|
|
user_collection_id: userCollectionId,
|
|
entry_id: entryId
|
|
}
|
|
});
|
|
|
|
if (!collectionEntry) {
|
|
res.status(404).json({ message: 'UserCollectionEntry not found.' });
|
|
}
|
|
|
|
// ? updating
|
|
await collectionEntry.update({ order: newOrder });
|
|
|
|
res.status(200).json({ message: 'UserCollectionEntry order updated successfully.' });
|
|
} catch (error) {
|
|
console.log(`Error Updating UserCollectionEntry order: `, error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// * DELETE - REMOVE AN ENTRY FROM A UserCollection
|
|
router.delete('/:userCollectionId/entries/:entryId', async (req, res) => {
|
|
try {
|
|
const { userCollectionId, entryId } = req.params;
|
|
const deleted = await UserCollectionEntry.findOne({
|
|
where: {
|
|
user_collection_id: userCollectionId,
|
|
entry_id: entryId
|
|
}
|
|
});
|
|
console.log(`deleteing : `, deleted)
|
|
|
|
const deletedCount = deleted.destroy();
|
|
|
|
if (deleted) {
|
|
res.status(204).send();
|
|
} else {
|
|
res.status(404).json({ message: 'UserCollection entry not found.' });
|
|
}
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// * POST - CREATE UserCollection WITH ENTRY
|
|
router.post('/lists-with-entry', async (req, res) => {
|
|
const { listDetails, entryId, entryOrder } = req.body; // Destructure needed properties from the request body
|
|
|
|
try {
|
|
const result = await sequelize.transaction(async (t) => {
|
|
// Step 1: Create the userCollection
|
|
const newUserCollection = await UserCollection.create(listDetails, { transaction: t });
|
|
|
|
// Step 2: Add an entry to the newly created userCollection
|
|
const newUserCollectionEntry = await UserCollectionEntry.create({
|
|
userCollectionId: newUserCollection.id,
|
|
entryId: entryId,
|
|
entryOrder: entryOrder
|
|
}, { transaction: t });
|
|
|
|
return { newUserCollection, newUserCollectionEntry };
|
|
});
|
|
|
|
// If the transaction is successful, send back the created userCollection and entry relationship
|
|
res.status(201).json(result);
|
|
} catch (error) {
|
|
console.error('Failed to create userCollection and add entry:', error);
|
|
res.status(500).json({ message: 'Failed to create userCollection and add entry', error: error.message });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|