From 702cd537d1b1f6b68ca6dc1c365437cb44147a04 Mon Sep 17 00:00:00 2001 From: X4Lo Date: Fri, 29 May 2026 02:57:28 +0100 Subject: [PATCH] fix(ai-query): two-step query for recently-watched endpoints to avoid genre join row multiplication --- backend/controllers/aiQueryController.js | 64 ++++++++++++++++++++---- 1 file changed, 54 insertions(+), 10 deletions(-) diff --git a/backend/controllers/aiQueryController.js b/backend/controllers/aiQueryController.js index d083d5e..56532a0 100644 --- a/backend/controllers/aiQueryController.js +++ b/backend/controllers/aiQueryController.js @@ -49,7 +49,28 @@ class AiQueryController { getRecentlyWatchedMovies = asyncWrapper(async (req, res) => { const limit = Math.min(parseInt(req.query.limit) || 10, 50); + // Step 1: Get the last N EntrySeen IDs for movies (simple query, no genre joins) + const seenIds = await EntrySeen.findAll({ + attributes: ['id'], + include: [{ + model: Entry, + as: 'entry', + attributes: [], + where: { is_tvseries: false, hidden: false } + }], + order: [['date_seen', 'DESC'], ['id', 'DESC']], + limit + }); + + if (seenIds.length === 0) { + return res.status(200).json([]); + } + + const idList = seenIds.map(s => s.id); + + // Step 2: Fetch full data for those IDs with all joins const entries = await EntrySeen.findAll({ + where: { id: idList }, include: [{ model: Entry, as: 'entry', @@ -59,13 +80,7 @@ class AiQueryController { ], attributes: ['id', 'title', 'is_tvseries', 'poster_path', 'banner_path', 'runtime', 'release_date', 'favorit', 'watchlist'] }], - where: { - '$entry.is_tvseries$': false, - '$entry.hidden$': false - }, - order: [['date_seen', 'DESC'], ['id', 'DESC']], - limit, - subQuery: false + order: [['date_seen', 'DESC'], ['id', 'DESC']] }); const result = entries.map(es => ({ @@ -94,7 +109,38 @@ class AiQueryController { getRecentlyWatchedEpisodes = asyncWrapper(async (req, res) => { const limit = Math.min(parseInt(req.query.limit) || 10, 50); + // Step 1: Get the last N EpisodeSeen IDs (simple query, no nested joins) + const seenIds = await EpisodeSeen.findAll({ + attributes: ['id'], + include: [{ + model: Episode, + as: 'episode', + attributes: [], + include: [{ + model: Season, + as: 'season', + attributes: [], + include: [{ + model: Entry, + as: 'entry', + attributes: [], + where: { hidden: false } + }] + }] + }], + order: [['date_seen', 'DESC'], ['id', 'DESC']], + limit + }); + + if (seenIds.length === 0) { + return res.status(200).json([]); + } + + const idList = seenIds.map(s => s.id); + + // Step 2: Fetch full data for those IDs with all joins const records = await EpisodeSeen.findAll({ + where: { id: idList }, include: [{ model: Episode, as: 'episode', @@ -111,9 +157,7 @@ class AiQueryController { }] }] }], - order: [['date_seen', 'DESC'], ['id', 'DESC']], - limit, - subQuery: false + order: [['date_seen', 'DESC'], ['id', 'DESC']] }); const result = records.map(es => ({