From f8d46cae585d28c9a8dec0e738f987c6e8a50484 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 26 Jul 2023 15:40:29 -0500 Subject: [PATCH] Trends: fill in empty tag histories Fixes https://gitlab.com/soapbox-pub/ditto/-/issues/29 --- src/controllers/api/trends.ts | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/controllers/api/trends.ts b/src/controllers/api/trends.ts index cadfecf..916bf0a 100644 --- a/src/controllers/api/trends.ts +++ b/src/controllers/api/trends.ts @@ -29,7 +29,7 @@ const trendingTagsController: AppController = (c) => { accounts: String(accounts), uses: String(uses), }, - ...trends.getTagHistory({ + ...getTagHistoryWithGapsFilled({ tag: name, since: lastWeek, until: now, @@ -44,4 +44,28 @@ const trendingTagsController: AppController = (c) => { }))); }; +function generateDateRange(since: Date, until: Date): Date[] { + const dates = []; + + const sinceDate = new Date(Date.UTC(since.getUTCFullYear(), since.getUTCMonth(), since.getUTCDate() + 1)); + const untilDate = new Date(Date.UTC(until.getUTCFullYear(), until.getUTCMonth(), until.getUTCDate())); + + while (sinceDate < untilDate) { + dates.push(new Date(sinceDate)); + sinceDate.setUTCDate(sinceDate.getUTCDate() + 1); + } + + return dates.reverse(); +} + +function getTagHistoryWithGapsFilled(params: Parameters[0]) { + const history = trends.getTagHistory(params); + const dateRange = generateDateRange(params.since, params.until); + + return dateRange.map((day) => { + const data = history.find((item) => item.day.getTime() === day.getTime()); + return data || { day, accounts: 0, uses: 0 }; + }); +} + export { trendingTagsController };