This commit is contained in:
2026-01-26 10:21:44 +01:00
parent 46fb7067ed
commit 588ab3c3de

View File

@@ -25,56 +25,24 @@ export default router => {
const hasSession = !!req.session;
const modequery = mime.startsWith("audio") ? lib.getMode(0) : lib.getMode(req.session?.mode ?? 0);
// ID Seek Strategy
const maxIdResult = await db`select max(id) as id from "items"`;
const maxId = maxIdResult[0].id || 0;
let tagId = null;
if (tag) {
const tagResult = await db`select id from "tags" where normalized ilike '%' || slugify(${tag}) || '%' limit 1`;
if (tagResult.length === 0) {
return res.json({ success: false, items: [] });
}
tagId = tagResult[0].id;
}
// Reusable query parts
const baseQuery = db`
const rows = await db`
select "items".*
from "items"
${isFav
? db`join "favorites" on "favorites".item_id = "items".id join "user" as fu on fu.id = "favorites".user_id`
: db``
}
left join tags_assign on tags_assign.item_id = items.id
left join tags on tags.id = tags_assign.tag_id
where
${db.unsafe(modequery)} and
mime ilike ${mime} and
active = 'true'
${isFav ? db`and fu."user" = ${user}` : db`and items.username ilike ${user}`}
${tagId ? db`and exists (select 1 from tags_assign where item_id = items.id and tag_id = ${tagId})` : db``}
${tag ? db`and tags.normalized ilike '%' || slugify(${tag}) || '%'` : db``}
${!hasSession && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(globalfilter)}))` : db``}
`;
// Optimized Count + Offset Strategy
const count = await db`
select count(*) as total
${baseQuery}
`;
if (count[0].total == 0) {
return res.json({
success: false,
items: []
});
}
const offset = Math.floor(Math.random() * count[0].total);
const rows = await db`
select "items".*
${baseQuery}
limit 1 offset ${offset}
order by random()
limit 1
`;
return res.json({