Trends: support `limit` param

This commit is contained in:
Alex Gleason 2023-07-25 17:44:38 -05:00
parent 48b7310d52
commit cbb294dbc2
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
3 changed files with 11 additions and 5 deletions

View File

@ -1,13 +1,19 @@
import { type AppController } from '@/app.ts'; import { type AppController } from '@/app.ts';
import { Conf } from '@/config.ts'; import { Conf } from '@/config.ts';
import { z } from '@/deps.ts';
import { trends } from '@/trends.ts'; import { trends } from '@/trends.ts';
import { Time } from '@/utils.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 trendingTagsController: AppController = (c) => {
const limit = limitSchema.parse(c.req.query('limit'));
if (limit < 1) return c.json([]);
const now = new Date(); const now = new Date();
const yesterday = new Date(now.getTime() - Time.days(1)); 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 }) => ({ return c.json(tags.map(({ name, accounts, uses }) => ({
name, name,

View File

@ -25,7 +25,7 @@ class TrendsDB {
}, Time.days(1)); }, Time.days(1));
} }
getTrendingTags(since: Date, until: Date) { getTrendingTags(since: Date, until: Date, limit = 10) {
return this.#db.query<string[]>( return this.#db.query<string[]>(
` `
SELECT tag, COUNT(DISTINCT pubkey8), COUNT(*) SELECT tag, COUNT(DISTINCT pubkey8), COUNT(*)
@ -33,9 +33,9 @@ class TrendsDB {
WHERE inserted_at >= ? AND inserted_at < ? WHERE inserted_at >= ? AND inserted_at < ?
GROUP BY tag GROUP BY tag
ORDER BY COUNT(DISTINCT pubkey8) ORDER BY COUNT(DISTINCT pubkey8)
DESC LIMIT 10; DESC LIMIT ?;
`, `,
[since, until], [since, until, limit],
).map((row) => ({ ).map((row) => ({
name: row[0], name: row[0],
accounts: Number(row[1]), accounts: Number(row[1]),

View File

@ -81,7 +81,7 @@ async function parseBody(req: Request): Promise<unknown> {
const paginationSchema = z.object({ const paginationSchema = z.object({
since: z.coerce.number().optional().catch(undefined), since: z.coerce.number().optional().catch(undefined),
until: z.lazy(() => z.coerce.number().catch(nostrNow())), 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<typeof paginationSchema>; type PaginationParams = z.infer<typeof paginationSchema>;