From cbb294dbc21dc6128d3cc7221f3a4ee928d7d332 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 25 Jul 2023 17:44:38 -0500 Subject: [PATCH] Trends: support `limit` param --- src/controllers/api/trends.ts | 8 +++++++- src/trends.ts | 6 +++--- src/utils.ts | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/controllers/api/trends.ts b/src/controllers/api/trends.ts index d4a4f7e..a8d74bc 100644 --- a/src/controllers/api/trends.ts +++ b/src/controllers/api/trends.ts @@ -1,13 +1,19 @@ import { type AppController } from '@/app.ts'; import { Conf } from '@/config.ts'; +import { z } from '@/deps.ts'; import { trends } from '@/trends.ts'; import { Time } from '@/utils.ts'; +const limitSchema = z.coerce.number().catch(10).transform((value) => Math.min(Math.max(value, 0), 20)); + const trendingTagsController: AppController = (c) => { + const limit = limitSchema.parse(c.req.query('limit')); + if (limit < 1) return c.json([]); + const now = new Date(); const yesterday = new Date(now.getTime() - Time.days(1)); - const tags = trends.getTrendingTags(yesterday, now); + const tags = trends.getTrendingTags(yesterday, now, limit); return c.json(tags.map(({ name, accounts, uses }) => ({ name, diff --git a/src/trends.ts b/src/trends.ts index 86a2873..2c28396 100644 --- a/src/trends.ts +++ b/src/trends.ts @@ -25,7 +25,7 @@ class TrendsDB { }, Time.days(1)); } - getTrendingTags(since: Date, until: Date) { + getTrendingTags(since: Date, until: Date, limit = 10) { return this.#db.query( ` SELECT tag, COUNT(DISTINCT pubkey8), COUNT(*) @@ -33,9 +33,9 @@ class TrendsDB { WHERE inserted_at >= ? AND inserted_at < ? GROUP BY tag ORDER BY COUNT(DISTINCT pubkey8) - DESC LIMIT 10; + DESC LIMIT ?; `, - [since, until], + [since, until, limit], ).map((row) => ({ name: row[0], accounts: Number(row[1]), diff --git a/src/utils.ts b/src/utils.ts index 7a91fc2..a81c0fd 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -81,7 +81,7 @@ async function parseBody(req: Request): Promise { const paginationSchema = z.object({ since: z.coerce.number().optional().catch(undefined), until: z.lazy(() => z.coerce.number().catch(nostrNow())), - limit: z.coerce.number().min(0).max(40).catch(20), + limit: z.coerce.number().catch(20).transform((value) => Math.min(Math.max(value, 0), 40)), }); type PaginationParams = z.infer;