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 entryManager = require('../services/entryManager');
const entryService = require("../services/entryService");
const asyncWrapper = require('../utils/asyncWrapper');
const _collectionManager = collectionManager;
const _entryManager = entryManager;
@@ -15,78 +16,77 @@ class EntryController {
}
return EntryController.instance;
}
// * GET ENTRY BY ID
async getAllEntries(req, res) {
getAllEntries = asyncWrapper(async (req, res) => {
const entries = await _entryService.getAllEntries();
res.status(200).json(entries);
}
});
// * GET ENTRY BY ID
async getEntryById(req, res) {
getEntryById = asyncWrapper(async (req, res) => {
const { id } = req.params;
let entry = await _entryManager.getUpdatedEntry(id);
res.status(200).json(entry);
}
});
// * 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 createdEntry = await _entryManager.fetchAndSaveNewEntry(tmdb_id, is_tvserie);
res.status(201).json(createdEntry);
}
});
// * PUT - ENTRY UPDATE
async updateEntry(req, res) {
updateEntry = asyncWrapper(async (req, res) => {
const { id } = req.params;
const { entryData } = req.body;
const updatedEntry = await _entryService.updateEntryById(id, entryData, true);
res.status(201).json(updatedEntry);
}
});
// * PUT - ENTRY Ratings UPDATE
async updateEntryRatings(req, res) {
updateEntryRatings = asyncWrapper(async (req, res) => {
const { id } = req.params;
const { entryRatings } = req.body;
const updatedEntryRatings = await _entryService.updateEntryRatings(id, entryRatings);
res.status(200).json(updatedEntryRatings);
}
});
// * PUT - ENTRY Ratings UPDATE
async updateEntryIds(req, res) {
updateEntryIds = asyncWrapper(async (req, res) => {
const { id } = req.params;
const { entryIds } = req.body;
const updatedEntryIds = await _entryService.updateEntryRatings(id, entryIds);
res.status(200).json(updatedEntryIds);
}
});
// * DELETE - ENTRY BY ID
async deleteEntry(req, res) {
deleteEntry = asyncWrapper(async (req, res) => {
const { id } = req.params;
await _entryService.deleteEntryById(id);
res.status(200).json({ message: `Entry with ID ${id} deleted.` });
}
});
// * GET - SYNC ALL ENTIRES DATA
async syncSeries(req, res, next) {
syncSeries = asyncWrapper(async (req, res, next) => {
const entries = await _entryManager.SyncSeriesData();
res.status(201).json(entries);
}
});
// * GET - Get seasons of an entry
async getEntrySeasons(req, res) {
getEntrySeasons = asyncWrapper(async (req, res) => {
const { id } = req.params;
const seasons = await _entryService.getEntrySeasons(id)
@@ -96,18 +96,18 @@ class EntryController {
}
res.status(200).json(seasons);
}
});
// * PUT - REQUEST ENTRY REFRECH
async refrechEntry(req, res, next) {
refrechEntry = asyncWrapper(async (req, res, next) => {
const { id } = req.params;
const entry = await _entryManager.refrechEntryById(id)
res.status(201).json(entry);
}
});
// * PUT - REQUEST COLLECTION REFRECH
async fetchEntryCollection(req, res, next) {
fetchEntryCollection = asyncWrapper(async (req, res, next) => {
const { id } = req.params;
const collection = await _collectionManager.fetchCollectionByEntryId(id);
@@ -117,7 +117,7 @@ class EntryController {
} else {
res.status(204);
}
}
});
}
module.exports = new EntryController();
+3 -3
View File
@@ -8,6 +8,7 @@ const Collection = require('../models/Collection');
const configService = require('../services/configService.js');
const { logToFile } = require('../services/logService');
const mediaOptimizerService = require('../services/mediaOptimizerService.js');
const asyncWrapper = require('../utils/asyncWrapper');
const _mediaOptimizerService = mediaOptimizerService;
@@ -19,8 +20,7 @@ class MediaController {
}
return MediaController.instance;
}
async getMedias(req, res) {
getMedias = asyncWrapper(async (req, res) => {
const allCustomMedia = await Media.findAll({
where: {
@@ -41,7 +41,7 @@ class MediaController {
});
res.status(200).json(allCustomMedia);
}
});
getMedia(req, res, next) {
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');
module.exports = (err, req, res, next) => {
// Log the error for debugging purposes
console.log(`📌 Error caught in middleware:`, err);
if (err instanceof CustomError) {
res.status(err.statusCode()).json({ message: err.message });
logToFile(`Error (${err.statusCode()}) ${err.message}`)
logToFile(`Custom Error (${err.statusCode()}) - ${req.method} ${req.path}: ${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 {
console.log(`📌 Error: `, err)
logToFile(`Error (500) ${err}`)
res.status(500).json({ message: 'Internal server error' });
// Handle all other errors
const errorMessage = err.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();
// 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 sequelizeHooks = require('./config/sequelizeHooks.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 mediaManager = require("./mediaManager.js");
const networkService = require("./networkService.js");
const InternalServerError = require("../errors/InternalServerError.js");
const _collectionManager = collectionManager;
const _entryService = entryService;
@@ -56,6 +57,7 @@ class EntryManager {
// * 2 - insert the entry into db
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
if (entryData.belongs_to_collection && fetchCollection) {
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);
if (!entryData)
throw ValidationError(`Couldn't Fetch Entry Data`);
throw new ValidationError(`Couldn't Fetch Entry Data`);
// ! 1 - Normal Data
let newData = {
+3
View File
@@ -121,6 +121,7 @@ class EntryService {
async createEntry(data, plain = true) {
// creating the object
var is_tvseries = data.release_date == null ? true : false;
console.log('entryService > createEntry > is_tvseries: ', is_tvseries);
let movie = Entry.build({
title: data.title || data.name,
@@ -147,6 +148,8 @@ class EntryService {
let savedEntry = await movie.save();
console.log('entryService > createEntry > savedEntry: ', savedEntry);
// ? ids
await EntryId.create({
entry_id: savedEntry.id,
@@ -660,7 +660,7 @@ async function SyncSerieData(entryId) {
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (!entryData)
throw ValidationError(`Couldn't Fetch Entry Data`);
throw new ValidationError(`Couldn't Fetch Entry Data`);
// ! 1 - Normal Data
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;