From 3410842e1108c282a4952cf1162f6fdceeb97c62 Mon Sep 17 00:00:00 2001 From: Michael Liendo Date: Tue, 24 Sep 2024 07:55:49 -0400 Subject: [PATCH] feat(core): add post sorting functionality in repository --- crates/core/src/post/repository.rs | 23 +++++++++++++++++-- .../server/src/graphql/modules/user/types.rs | 1 + 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/core/src/post/repository.rs b/crates/core/src/post/repository.rs index 31c9d972..b04b60ee 100644 --- a/crates/core/src/post/repository.rs +++ b/crates/core/src/post/repository.rs @@ -3,8 +3,8 @@ use std::str::FromStr; use chrono::{DateTime, Utc}; use pxid::Pxid; use sea_orm::{ - ActiveModelTrait, ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, QuerySelect, Set, - TransactionTrait, + ActiveModelTrait, ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, QueryOrder, + QuerySelect, Set, TransactionTrait, }; use serde::{Deserialize, Serialize}; @@ -13,6 +13,12 @@ use crate::shared::database::Database; use crate::shared::pagination::Pagination; use crate::shared::query_set::QuerySet; +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum PostSortBy { + CreatedAtAsc, + CreatedAtDesc, +} + #[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] pub struct PostRecord { pub id: String, @@ -43,6 +49,7 @@ pub struct PostRepository { #[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)] pub struct PostFilter { pub author_id: Option, + pub sort_by: Option, } impl PostRepository { @@ -77,6 +84,18 @@ impl PostRepository { if let Some(id) = filter.author_id { query = query.filter(entity::post::Column::AuthorId.eq(id.to_string())); } + + match filter.sort_by { + Some(PostSortBy::CreatedAtAsc) => { + query = query.order_by_asc(entity::post::Column::CreatedAt); + } + Some(PostSortBy::CreatedAtDesc) => { + query = query.order_by_desc(entity::post::Column::CreatedAt); + } + None => { + query = query.order_by_desc(entity::post::Column::CreatedAt); + } + } } let count = query diff --git a/crates/server/src/graphql/modules/user/types.rs b/crates/server/src/graphql/modules/user/types.rs index 2a82b4a7..5c526e94 100644 --- a/crates/server/src/graphql/modules/user/types.rs +++ b/crates/server/src/graphql/modules/user/types.rs @@ -94,6 +94,7 @@ impl User { Some(pagination), Some(PostFilter { author_id: Some(self.id), + sort_by: None, }), ) .await?;