Skip to content

Commit 36526d5

Browse files
authored
1 parent 9b51613 commit 36526d5

File tree

3 files changed

+33
-7
lines changed

3 files changed

+33
-7
lines changed

backend/src/api/routes/ideas.py

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
from collections.abc import Mapping, Sequence
12
from contextlib import suppress
2-
from typing import Annotated
3+
from typing import Annotated, Any
34

45
from fastapi import APIRouter, HTTPException
56
from odmantic import ObjectId
@@ -31,8 +32,31 @@ async def create_idea(
3132

3233

3334
@router.get("/", response_model=IdeasPublic)
34-
async def get_ideas(db: Db, skip: int = 0, limit: int = 20):
35-
ideas = await db.find(Idea, limit=limit, skip=skip)
35+
async def get_ideas(db: Db, skip: int = 0, limit: int = 20, sort: str | None = None):
36+
if sort == "trending":
37+
collection = db.engine.get_collection(Idea)
38+
aggregates: Sequence[Mapping[str, Any]] = [
39+
{
40+
"$project": {
41+
"_id": 1,
42+
"name": 1,
43+
"description": 1,
44+
"upvoted_by": 1,
45+
"downvoted_by": 1,
46+
"creator_id": 1,
47+
"upvotes": {"$size": "$upvoted_by"},
48+
}
49+
},
50+
{"$sort": {"upvotes": -1}},
51+
{"$skip": skip},
52+
{"$limit": limit},
53+
]
54+
results = await collection.aggregate(aggregates).to_list(length=None)
55+
ideas = [Idea.model_validate_doc(result) for result in results]
56+
# elif sort == 'newest':
57+
# pass
58+
else:
59+
ideas = await db.find(Idea, limit=limit, skip=skip, sort=Idea.name)
3660
count = await db.count(Idea)
3761
return IdeasPublic(
3862
data=[IdeaPublic(**idea.model_dump()) for idea in ideas], count=count

frontend/src/App.jsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ function App() {
2828
path=''
2929
element={
3030
<>
31-
<IdeaFormSection count='3' />
31+
<IdeaFormSection count='3' sort='trending' />
3232
<IdeaSubmissionForm />
3333
<LandingPageContent />
3434
</>

frontend/src/components/IdeaFormSection.jsx

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,16 @@ import { useApi } from '../hooks/useApi';
33
import { Link } from 'react-router';
44
import UpvoteImg from '../assets/Upvote.svg';
55

6-
const IdeaFormSection = ({ count }) => {
6+
const IdeaFormSection = ({ count, sort = null }) => {
77
const { isLoading, error, data, fetchFromApi } = useApi({
88
loadingInitially: true,
99
});
1010

11+
const sorting = sort ? `&sort=${sort}` : '';
12+
1113
useEffect(() => {
12-
fetchFromApi(`/ideas/?limit=${count}`);
13-
}, [count, fetchFromApi]);
14+
fetchFromApi(`/ideas/?limit=${count}${sorting}`);
15+
}, [count, fetchFromApi, sorting]);
1416

1517
return (
1618
<section className='idea-form-section'>

0 commit comments

Comments
 (0)