From 91546a1f0d37c7e4c134e2c67ae032cbfc4885b0 Mon Sep 17 00:00:00 2001 From: Kibi Kelburton Date: Mon, 26 Jan 2026 10:04:53 +0100 Subject: [PATCH] lets try it out lmao --- src/inc/routes/apiv2/index.mjs | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/src/inc/routes/apiv2/index.mjs b/src/inc/routes/apiv2/index.mjs index 2e90ab0..ba9a8e6 100644 --- a/src/inc/routes/apiv2/index.mjs +++ b/src/inc/routes/apiv2/index.mjs @@ -29,7 +29,7 @@ export default router => { const maxIdResult = await db`select max(id) as id from "items"`; const maxId = maxIdResult[0].id || 0; - const randomId = Math.floor(Math.random() * maxId); + let tagId = null; if (tag) { @@ -57,24 +57,27 @@ export default router => { ${!hasSession && globalfilter ? db`and not exists (select 1 from tags_assign where item_id = items.id and (${db.unsafe(globalfilter)}))` : db``} `; - // Try seeking forward from random ID - let rows = await db` + // Optimized Count + Offset Strategy + const count = await db` + select count(*) as total ${baseQuery} - and "items".id >= ${randomId} - order by "items".id asc - limit 1 `; - // Fallback: wrap around if nothing found - if (rows.length === 0) { - rows = await db` - ${baseQuery} - and "items".id >= 0 - order by "items".id asc - limit 1 - `; + 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} + `; + return res.json({ success: rows.length > 0, items: rows.length > 0 ? rows[0] : []