diff --git a/src/routes/posts/postsDiscover.ts b/src/routes/posts/postsDiscover.ts index 8a117ab2..ac6fec5c 100644 --- a/src/routes/posts/postsDiscover.ts +++ b/src/routes/posts/postsDiscover.ts @@ -21,8 +21,10 @@ interface Query { limit?: string; afterId?: string; beforeId?: string; + sort?: string; } +const SortOptions = ['mostLiked30days', 'mostLikedAllTime']; async function route(req: Request, res: Response) { const query = req.query as Query; @@ -34,6 +36,16 @@ async function route(req: Request, res: Response) { limit = undefined; } + const sort = SortOptions.includes(query.sort!) ? query.sort : undefined; + + let afterDate: Date | undefined = undefined; + + if (sort) { + if (sort === 'mostLiked30days') { + afterDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); + } + } + const posts = await fetchPosts({ hideIfBlockedByMe: true, withReplies: false, @@ -42,6 +54,23 @@ async function route(req: Request, res: Response) { limit, afterId: query.afterId, beforeId: query.beforeId, + + ...(sort + ? { + orderBy: { + estimateLikes: 'asc', + }, + ...(afterDate + ? { + where: { + createdAt: { + gte: afterDate, + }, + }, + } + : {}), + } + : {}), }); res.json(posts); } diff --git a/src/services/Post.ts b/src/services/Post.ts index 30e98f31..b83c7ee7 100644 --- a/src/services/Post.ts +++ b/src/services/Post.ts @@ -163,6 +163,7 @@ interface FetchPostsOpts { where?: Prisma.PostWhereInput; additionalInclude?: Prisma.PostInclude; + orderBy?: Prisma.PostOrderByWithRelationInput; } export async function fetchPosts(opts: FetchPostsOpts) { @@ -201,7 +202,7 @@ export async function fetchPosts(opts: FetchPostsOpts) { const posts = await prisma.post.findMany({ where, - orderBy: { createdAt: 'desc' }, + orderBy: opts.orderBy || { createdAt: 'desc' }, take: opts.limit ? (opts.limit > 30 ? 30 : opts.limit) : 30, include: { ...constructInclude(opts.requesterUserId), ...opts.additionalInclude }, });