diff --git a/src/controllers/api/trends.ts b/src/controllers/api/trends.ts index 99c2d7b..2590d4c 100644 --- a/src/controllers/api/trends.ts +++ b/src/controllers/api/trends.ts @@ -12,6 +12,7 @@ const trendingTagsController: AppController = (c) => { const now = new Date(); const yesterday = new Date(now.getTime() - Time.days(1)); + const lastWeek = new Date(now.getTime() - Time.days(7)); const tags = trends.getTrendingTags({ since: yesterday, @@ -19,14 +20,14 @@ const trendingTagsController: AppController = (c) => { limit, }); - return c.json(tags.map(({ name, accounts, uses }) => ({ + return c.json(tags.map(({ name }) => ({ name, url: Conf.local(`/tags/${name}`), - history: [{ - day: String(Math.floor(yesterday.getTime() / 1000)), - uses: String(uses), - accounts: String(accounts), - }], + history: trends.getTagHistory(name, lastWeek, now).map((history) => ({ + day: String(Math.floor(history.day.getTime() / 1000)), + accounts: String(history.accounts), + uses: String(history.uses), + })), }))); }; diff --git a/src/trends.ts b/src/trends.ts index a74fd46..f266a1f 100644 --- a/src/trends.ts +++ b/src/trends.ts @@ -54,6 +54,23 @@ class TrendsDB { })); } + getTagHistory(tag: string, since: Date, until: Date) { + return this.#db.query( + ` + SELECT inserted_at, COUNT(DISTINCT pubkey8), COUNT(*) + FROM tag_usages + WHERE tag = ? AND inserted_at >= ? AND inserted_at < ? + GROUP BY date(inserted_at) + ORDER BY date(inserted_at); + `, + [tag, since, until], + ).map((row) => ({ + day: new Date(row[0]), + accounts: Number(row[1]), + uses: Number(row[2]), + })); + } + addTagUsages(pubkey: string, hashtags: string[], date = new Date()): void { const pubkey8 = hexIdSchema.parse(pubkey).substring(0, 8); const tags = hashtagSchema.array().min(1).parse(hashtags);