Skip to content

Commit

Permalink
sort by most liked post
Browse files Browse the repository at this point in the history
  • Loading branch information
SupertigerDev committed Oct 27, 2024
1 parent 891ca73 commit 4edb1d6
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
29 changes: 29 additions & 0 deletions src/routes/posts/postsDiscover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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,
Expand All @@ -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);
}
3 changes: 2 additions & 1 deletion src/services/Post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ interface FetchPostsOpts {

where?: Prisma.PostWhereInput;
additionalInclude?: Prisma.PostInclude;
orderBy?: Prisma.PostOrderByWithRelationInput;
}

export async function fetchPosts(opts: FetchPostsOpts) {
Expand Down Expand Up @@ -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 },
});
Expand Down

0 comments on commit 4edb1d6

Please sign in to comment.