Backend: Implement async error handling wrapper and refactor entry and media controllers to use it

This commit is contained in:
X4Lo committed 2026-03-30 17:25:46 +01:00
1 parent ad58164df4
commit 4a1d2bc614
8 files changed
+92 -33

No files matched your search

+23 -23
View File
@@ -2,6 +2,7 @@ const EntryRating = require('../models/EntryRating');
const collectionManager = require('../services/collectionManager'); const collectionManager = require('../services/collectionManager');
const entryManager = require('../services/entryManager'); const entryManager = require('../services/entryManager');
const entryService = require("../services/entryService"); const entryService = require("../services/entryService");
const asyncWrapper = require('../utils/asyncWrapper');
const _collectionManager = collectionManager; const _collectionManager = collectionManager;
const _entryManager = entryManager; const _entryManager = entryManager;
@@ -15,78 +16,77 @@ class EntryController {
} }
return EntryController.instance; return EntryController.instance;
} }
// * GET ENTRY BY ID // * GET ENTRY BY ID
async getAllEntries(req, res) { getAllEntries = asyncWrapper(async (req, res) => {
const entries = await _entryService.getAllEntries(); const entries = await _entryService.getAllEntries();
res.status(200).json(entries); res.status(200).json(entries);
} });
// * GET ENTRY BY ID // * GET ENTRY BY ID
async getEntryById(req, res) { getEntryById = asyncWrapper(async (req, res) => {
const { id } = req.params; const { id } = req.params;
let entry = await _entryManager.getUpdatedEntry(id); let entry = await _entryManager.getUpdatedEntry(id);
res.status(200).json(entry); res.status(200).json(entry);
} });
// * POST - FETCH AND CREATE ENTRY USING TMDB ID // * POST - FETCH AND CREATE ENTRY USING TMDB ID
async fetchAndSaveNewEntry(req, res) { fetchAndSaveNewEntry = asyncWrapper(async (req, res) => {
const { tmdb_id, is_tvserie } = req.body; const { tmdb_id, is_tvserie } = req.body;
const createdEntry = await _entryManager.fetchAndSaveNewEntry(tmdb_id, is_tvserie); const createdEntry = await _entryManager.fetchAndSaveNewEntry(tmdb_id, is_tvserie);
res.status(201).json(createdEntry); res.status(201).json(createdEntry);
} });
// * PUT - ENTRY UPDATE // * PUT - ENTRY UPDATE
async updateEntry(req, res) { updateEntry = asyncWrapper(async (req, res) => {
const { id } = req.params; const { id } = req.params;
const { entryData } = req.body; const { entryData } = req.body;
const updatedEntry = await _entryService.updateEntryById(id, entryData, true); const updatedEntry = await _entryService.updateEntryById(id, entryData, true);
res.status(201).json(updatedEntry); res.status(201).json(updatedEntry);
} });
// * PUT - ENTRY Ratings UPDATE // * PUT - ENTRY Ratings UPDATE
async updateEntryRatings(req, res) { updateEntryRatings = asyncWrapper(async (req, res) => {
const { id } = req.params; const { id } = req.params;
const { entryRatings } = req.body; const { entryRatings } = req.body;
const updatedEntryRatings = await _entryService.updateEntryRatings(id, entryRatings); const updatedEntryRatings = await _entryService.updateEntryRatings(id, entryRatings);
res.status(200).json(updatedEntryRatings); res.status(200).json(updatedEntryRatings);
} });
// * PUT - ENTRY Ratings UPDATE // * PUT - ENTRY Ratings UPDATE
async updateEntryIds(req, res) { updateEntryIds = asyncWrapper(async (req, res) => {
const { id } = req.params; const { id } = req.params;
const { entryIds } = req.body; const { entryIds } = req.body;
const updatedEntryIds = await _entryService.updateEntryRatings(id, entryIds); const updatedEntryIds = await _entryService.updateEntryRatings(id, entryIds);
res.status(200).json(updatedEntryIds); res.status(200).json(updatedEntryIds);
} });
// * DELETE - ENTRY BY ID // * DELETE - ENTRY BY ID
async deleteEntry(req, res) { deleteEntry = asyncWrapper(async (req, res) => {
const { id } = req.params; const { id } = req.params;
await _entryService.deleteEntryById(id); await _entryService.deleteEntryById(id);
res.status(200).json({ message: `Entry with ID ${id} deleted.` }); res.status(200).json({ message: `Entry with ID ${id} deleted.` });
} });
// * GET - SYNC ALL ENTIRES DATA // * GET - SYNC ALL ENTIRES DATA
async syncSeries(req, res, next) { syncSeries = asyncWrapper(async (req, res, next) => {
const entries = await _entryManager.SyncSeriesData(); const entries = await _entryManager.SyncSeriesData();
res.status(201).json(entries); res.status(201).json(entries);
} });
// * GET - Get seasons of an entry // * GET - Get seasons of an entry
async getEntrySeasons(req, res) { getEntrySeasons = asyncWrapper(async (req, res) => {
const { id } = req.params; const { id } = req.params;
const seasons = await _entryService.getEntrySeasons(id) const seasons = await _entryService.getEntrySeasons(id)
@@ -96,18 +96,18 @@ class EntryController {
} }
res.status(200).json(seasons); res.status(200).json(seasons);
} });
// * PUT - REQUEST ENTRY REFRECH // * PUT - REQUEST ENTRY REFRECH
async refrechEntry(req, res, next) { refrechEntry = asyncWrapper(async (req, res, next) => {
const { id } = req.params; const { id } = req.params;
const entry = await _entryManager.refrechEntryById(id) const entry = await _entryManager.refrechEntryById(id)
res.status(201).json(entry); res.status(201).json(entry);
} });
// * PUT - REQUEST COLLECTION REFRECH // * PUT - REQUEST COLLECTION REFRECH
async fetchEntryCollection(req, res, next) { fetchEntryCollection = asyncWrapper(async (req, res, next) => {
const { id } = req.params; const { id } = req.params;
const collection = await _collectionManager.fetchCollectionByEntryId(id); const collection = await _collectionManager.fetchCollectionByEntryId(id);
@@ -117,7 +117,7 @@ class EntryController {
} else { } else {
res.status(204); res.status(204);
} }
} });
} }
module.exports = new EntryController(); module.exports = new EntryController();
+3 -3
View File
@@ -8,6 +8,7 @@ const Collection = require('../models/Collection');
const configService = require('../services/configService.js'); const configService = require('../services/configService.js');
const { logToFile } = require('../services/logService'); const { logToFile } = require('../services/logService');
const mediaOptimizerService = require('../services/mediaOptimizerService.js'); const mediaOptimizerService = require('../services/mediaOptimizerService.js');
const asyncWrapper = require('../utils/asyncWrapper');
const _mediaOptimizerService = mediaOptimizerService; const _mediaOptimizerService = mediaOptimizerService;
@@ -19,8 +20,7 @@ class MediaController {
} }
return MediaController.instance; return MediaController.instance;
} }
getMedias = asyncWrapper(async (req, res) => {
async getMedias(req, res) {
const allCustomMedia = await Media.findAll({ const allCustomMedia = await Media.findAll({
where: { where: {
@@ -41,7 +41,7 @@ class MediaController {
}); });
res.status(200).json(allCustomMedia); res.status(200).json(allCustomMedia);
} });
getMedia(req, res, next) { getMedia(req, res, next) {
const { category, type, size, fileName } = req.params; const { category, type, size, fileName } = req.params;
+38 -5
View File
@@ -2,12 +2,45 @@ const CustomError = require('../errors/CustomError');
const { logToFile } = require('../services/logService'); const { logToFile } = require('../services/logService');
module.exports = (err, req, res, next) => { module.exports = (err, req, res, next) => {
// Log the error for debugging purposes
console.log(`📌 Error caught in middleware:`, err);
if (err instanceof CustomError) { if (err instanceof CustomError) {
res.status(err.statusCode()).json({ message: err.message }); logToFile(`Custom Error (${err.statusCode()}) - ${req.method} ${req.path}: ${err.message}`);
logToFile(`Error (${err.statusCode()}) ${err.message}`) res.status(err.statusCode()).json({
message: err.message,
error: process.env.NODE_ENV === 'development' ? err.stack : undefined
});
} else if (err.name === 'ValidationError') {
// Handle Sequelize validation errors
logToFile(`Validation Error - ${req.method} ${req.path}: ${err.message}`);
res.status(400).json({
message: 'Validation Error',
details: err.errors || err.message,
error: process.env.NODE_ENV === 'development' ? err.stack : undefined
});
} else if (err.name === 'SequelizeUniqueConstraintError') {
// Handle Sequelize unique constraint errors
logToFile(`Unique Constraint Error - ${req.method} ${req.path}: ${err.message}`);
res.status(409).json({
message: 'Duplicate entry detected',
error: process.env.NODE_ENV === 'development' ? err.stack : undefined
});
} else if (err.name === 'SequelizeForeignKeyConstraintError') {
// Handle foreign key constraint errors
logToFile(`Foreign Key Error - ${req.method} ${req.path}: ${err.message}`);
res.status(400).json({
message: 'Invalid reference to related data',
error: process.env.NODE_ENV === 'development' ? err.stack : undefined
});
} else { } else {
console.log(`📌 Error: `, err) // Handle all other errors
logToFile(`Error (500) ${err}`) const errorMessage = err.message || 'Internal server error';
res.status(500).json({ message: 'Internal server error' }); logToFile(`Unexpected Error - ${req.method} ${req.path}: ${errorMessage}\nStack: ${err.stack}`);
res.status(500).json({
message: 'Internal server error',
error: process.env.NODE_ENV === 'development' ? err.stack : undefined
});
} }
}; };
+13
View File
@@ -5,6 +5,19 @@ const sequelize = require('./config/database.js');
const app = express(); const app = express();
// Global error handling for unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
// Application specific logging, throwing an error, or other logic here
});
// Global error handling for uncaught exceptions
process.on('uncaughtException', (error) => {
console.log('Uncaught Exception:', error);
// Application specific logging, throwing an error, or other logic here
process.exit(1); // Exit the process to avoid undefined state
});
const relations = require('./config/relations.js'); const relations = require('./config/relations.js');
const sequelizeHooks = require('./config/sequelizeHooks.js'); const sequelizeHooks = require('./config/sequelizeHooks.js');
const { initializeData } = require('./config/dataInitializer.js'); const { initializeData } = require('./config/dataInitializer.js');
+3 -1
View File
@@ -23,6 +23,7 @@ const collectionManager = require('./collectionManager.js');
const entryService = require("./entryService"); const entryService = require("./entryService");
const mediaManager = require("./mediaManager.js"); const mediaManager = require("./mediaManager.js");
const networkService = require("./networkService.js"); const networkService = require("./networkService.js");
const InternalServerError = require("../errors/InternalServerError.js");
const _collectionManager = collectionManager; const _collectionManager = collectionManager;
const _entryService = entryService; const _entryService = entryService;
@@ -56,6 +57,7 @@ class EntryManager {
// * 2 - insert the entry into db // * 2 - insert the entry into db
const entry = await _entryService.createEntry(entryData, plain); const entry = await _entryService.createEntry(entryData, plain);
console.log('Entry created with ID:', entry.id, 'and title:', entry.title, 'and is_tvseries:', entry.is_tvseries);
// * 3 - created the related collection // * 3 - created the related collection
if (entryData.belongs_to_collection && fetchCollection) { if (entryData.belongs_to_collection && fetchCollection) {
await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id); await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id);
@@ -461,7 +463,7 @@ class EntryManager {
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries); const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (!entryData) if (!entryData)
throw ValidationError(`Couldn't Fetch Entry Data`); throw new ValidationError(`Couldn't Fetch Entry Data`);
// ! 1 - Normal Data // ! 1 - Normal Data
let newData = { let newData = {
+3
View File
@@ -121,6 +121,7 @@ class EntryService {
async createEntry(data, plain = true) { async createEntry(data, plain = true) {
// creating the object // creating the object
var is_tvseries = data.release_date == null ? true : false; var is_tvseries = data.release_date == null ? true : false;
console.log('entryService > createEntry > is_tvseries: ', is_tvseries);
let movie = Entry.build({ let movie = Entry.build({
title: data.title || data.name, title: data.title || data.name,
@@ -147,6 +148,8 @@ class EntryService {
let savedEntry = await movie.save(); let savedEntry = await movie.save();
console.log('entryService > createEntry > savedEntry: ', savedEntry);
// ? ids // ? ids
await EntryId.create({ await EntryId.create({
entry_id: savedEntry.id, entry_id: savedEntry.id,
@@ -660,7 +660,7 @@ async function SyncSerieData(entryId) {
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries); const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (!entryData) if (!entryData)
throw ValidationError(`Couldn't Fetch Entry Data`); throw new ValidationError(`Couldn't Fetch Entry Data`);
// ! 1 - Normal Data // ! 1 - Normal Data
let newData = { let newData = {
+8
View File
@@ -0,0 +1,8 @@
// Async wrapper utility to catch async errors and pass them to Express error handler
const asyncWrapper = (fn) => {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
module.exports = asyncWrapper;