From 9777a67a1e33862ea8acb5e58cb6548cf0f1fffb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9F=83=E6=8B=89?= Date: Mon, 16 Dec 2024 21:59:27 +0800 Subject: [PATCH] wip: sorts in game --- src/db/transfer/game.rs | 22 ++++++++++++++++++++-- src/db/transfer/game_team.rs | 2 +- src/web/router/api/game/mod.rs | 2 ++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/db/transfer/game.rs b/src/db/transfer/game.rs index 77a31877..9db8877f 100644 --- a/src/db/transfer/game.rs +++ b/src/db/transfer/game.rs @@ -1,4 +1,5 @@ -use sea_orm::{entity::prelude::*, QuerySelect}; +use std::str::FromStr; +use sea_orm::{entity::prelude::*, Order, QueryOrder, QuerySelect}; use serde::{Deserialize, Serialize}; use crate::db::{entity, get_db}; @@ -67,7 +68,7 @@ impl From for entity::game::Model { } pub async fn find( - id: Option, title: Option, is_enabled: Option, page: Option, + id: Option, title: Option, is_enabled: Option, sorts: Option, page: Option, size: Option, ) -> Result<(Vec, u64), DbErr> { let mut sql = entity::game::Entity::find(); @@ -84,6 +85,23 @@ pub async fn find( sql = sql.filter(entity::game::Column::IsEnabled.eq(is_enabled)); } + if let Some(sorts) = sorts { + let sorts = sorts.split(",").collect::>(); + for sort in sorts { + let col = match crate::db::entity::game::Column::from_str( + sort.replace("-", "").as_str(), + ) { + Ok(col) => col, + Err(_) => continue, + }; + if sort.starts_with("-") { + sql = sql.order_by(col, Order::Desc); + } else { + sql = sql.order_by(col, Order::Asc); + } + } + } + let total = sql.clone().count(get_db()).await?; if let Some(page) = page { diff --git a/src/db/transfer/game_team.rs b/src/db/transfer/game_team.rs index c9cb3987..9e8586e7 100644 --- a/src/db/transfer/game_team.rs +++ b/src/db/transfer/game_team.rs @@ -76,7 +76,7 @@ pub async fn find( sort.replace("-", "").as_str(), ) { Ok(col) => col, - Err(_) => return Err(DbErr::Custom("invalid sort column".to_string())), + Err(_) => continue, }; if sort.starts_with("-") { sql = sql.order_by(col, Order::Desc); diff --git a/src/web/router/api/game/mod.rs b/src/web/router/api/game/mod.rs index 749b61c5..3229a3d0 100644 --- a/src/web/router/api/game/mod.rs +++ b/src/web/router/api/game/mod.rs @@ -84,6 +84,7 @@ pub struct GetRequest { pub is_enabled: Option, pub page: Option, pub size: Option, + pub sorts: Option } pub async fn get( @@ -98,6 +99,7 @@ pub async fn get( params.id, params.title, params.is_enabled, + params.sorts, params.page, params.size, )