From c7e078d4950ef874f73f4d8668a88d6d31c11e9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bar=C4=B1=C5=9F=20Soner=20U=C5=9Fakl=C4=B1?= Date: Tue, 26 Oct 2021 15:51:42 -0400 Subject: [PATCH] refactor: dont save partial searches --- src/controllers/search.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/controllers/search.js b/src/controllers/search.js index 76a34d1e39..004fe67e3b 100644 --- a/src/controllers/search.js +++ b/src/controllers/search.js @@ -97,12 +97,26 @@ searchController.search = async function (req, res, next) { res.render('search', searchData); }; +const searches = {}; + async function recordSearch(data) { const { query, searchIn } = data; if (query) { const cleanedQuery = String(query).trim().toLowerCase().substr(0, 255); if (['titles', 'titlesposts', 'posts'].includes(searchIn) && cleanedQuery.length > 2) { - await db.sortedSetIncrBy('searches:all', 1, cleanedQuery); + searches[data.uid] = searches[data.uid] || { timeoutId: 0, queries: [] }; + searches[data.uid].queries.push(cleanedQuery); + if (searches[data.uid].timeoutId) { + clearTimeout(searches[data.uid].timeoutId); + } + searches[data.uid].timeoutId = setTimeout(async () => { + const copy = searches[data.uid].queries.slice(); + const filtered = searches[data.uid].queries.filter( + q => !copy.find(query => query.startsWith(q) && query.length > q.length) + ); + await Promise.all(filtered.map(query => db.sortedSetIncrBy('searches:all', 1, query))); + delete searches[data.uid]; + }, 5000); } } }