From 4e42c69690932592783e134abf81d4d253219e69 Mon Sep 17 00:00:00 2001 From: ayushtom Date: Wed, 1 Nov 2023 16:17:33 +0530 Subject: [PATCH] dev: add pagination in db query --- src/endpoints/leaderboard/get_ranking.rs | 31 +++++++++++++++++--- src/endpoints/leaderboard/get_static_info.rs | 5 ++-- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/endpoints/leaderboard/get_ranking.rs b/src/endpoints/leaderboard/get_ranking.rs index fff3039b..7e162131 100644 --- a/src/endpoints/leaderboard/get_ranking.rs +++ b/src/endpoints/leaderboard/get_ranking.rs @@ -11,8 +11,6 @@ (last_index === -1 then no previous page && last_index === total.documents.length then no next page) */ -// TODO: get paginated data - use crate::{models::AppState}; use axum::{ extract::{Query, State}, @@ -137,6 +135,15 @@ pub async fn handler( doc! { "$unwind": doc! { "path": "$docs", + "includeArrayIndex": "rownum", + + }, + }, + doc! { + "$addFields": { + "docs.rank": { + "$add": ["$rownum", 1], + }, }, }, doc! { @@ -144,15 +151,31 @@ pub async fn handler( "newRoot": "$docs", } }, + doc! { + "$match": doc!{ + "rank":doc!{ + "$gte":0, + "$lte":10 + } + } + }, + doc! { + "$project":{ + "_id":0, + "address":"$_id", + "total_points":1, + } + } ]; match users_collection.aggregate(paginated_leaderboard_pipeline, None).await { Ok(mut cursor) => { + let mut quest = Vec::new(); while let Some(result) = cursor.try_next().await.unwrap() { - println!("result: {}", result); + quest.push(result); } - (StatusCode::OK, Json("ehy")).into_response() + (StatusCode::OK, Json(quest)).into_response() } Err(_) => get_error("Error querying quests".to_string()), } diff --git a/src/endpoints/leaderboard/get_static_info.rs b/src/endpoints/leaderboard/get_static_info.rs index d98c7e6f..e3c59ced 100644 --- a/src/endpoints/leaderboard/get_static_info.rs +++ b/src/endpoints/leaderboard/get_static_info.rs @@ -41,7 +41,7 @@ pub async fn get_leaderboard_toppers( doc! { "$match": doc! { // Filter documents with a date field greater than or equal to one month ago - "timestamp": doc!{ + "timestamp": doc! { "$gte": time_gap } } @@ -64,6 +64,8 @@ pub async fn get_leaderboard_toppers( ], //getting the total number of users "totalUsers": vec![doc!{ "$count": "total" }], + + //getting the rank of the user "rank": vec![ doc! { "$group": { @@ -112,7 +114,6 @@ pub async fn get_leaderboard_toppers( "$first":"$rank.rank" } - }, }, ];