I'm trying to implement "sort by hot" similar to what HackerNews/Reddit do, as described here.
I want to calculate the rank of a post like so:
const age = new Date() - createdAt
const gravity = 1.8
const rankScore = (score - 1) / (age + 2) ** gravity
The Post
model has a score
value - how many upvotes the post has received, and createdAt
- the time it has been created. The higher the rankScore
is, the closer I want the post to be to the top of the list. So I want to take the score
and createdAt
values, use them to calculate rankScore
, and then do orderBy
by that.
What is the right way to implement this in Prisma?
Right now I'm just returning the list of most upvoted posts like so:
prisma.post.findMany({
where: {
authorId: authorId,
published: args.published || undefined,
},
orderBy: [{ score: "desc" }],
})
So it's easy to rank posts by a field that already exists on the model, but I need to calculate it in realtime, as the page loads, because rankScore
depends on post's age, and it wouldn't make sense to store something like this in the db.
Here's the actual resolver code I'm writing (see the posts
query).