diff --git a/src/models/mod.rs b/src/models/mod.rs index 3dbe65b..3384493 100644 --- a/src/models/mod.rs +++ b/src/models/mod.rs @@ -37,10 +37,11 @@ pub struct ListParams { } impl ListParams { - pub fn get_order_by(&self) -> String { - let default_order_by = "updated_at".to_string(); - let order_by = self.order_by.as_ref().unwrap_or(&default_order_by); - let order = self.order.as_ref().unwrap_or(&Order::Desc); - format!("{} {}", order_by, order) + pub fn get_order_by(&self) -> Option { + if let Some(order_by) = self.order_by.as_ref() { + let order = self.order.as_ref().unwrap_or(&Order::Desc); + return Some(format!("{} {}", order_by, order)); + } + None } } diff --git a/src/models/owner.rs b/src/models/owner.rs index 0825192..8c2f3fd 100644 --- a/src/models/owner.rs +++ b/src/models/owner.rs @@ -62,18 +62,31 @@ impl Model for Owner { async fn list(db: &PgPool, list_params: ListParams) -> Result> { let timer = std::time::Instant::now(); - let result = sqlx::query_as!( - Self, - "SELECT * FROM owners - ORDER BY $1 - LIMIT $2 - OFFSET $3", - list_params.get_order_by(), - list_params.limit.unwrap_or(10), - list_params.offset.unwrap_or(0), - ) - .fetch_all(db) - .await?; + let result = if let Some(order_by) = list_params.get_order_by() { + sqlx::query_as!( + Self, + "SELECT * FROM owners + ORDER BY $1 + LIMIT $2 + OFFSET $3", + order_by, + list_params.limit.unwrap_or(10), + list_params.offset.unwrap_or(0), + ) + .fetch_all(db) + .await? + } else { + sqlx::query_as!( + Self, + "SELECT * FROM owners + LIMIT $1 + OFFSET $2", + list_params.limit.unwrap_or(10), + list_params.offset.unwrap_or(0), + ) + .fetch_all(db) + .await? + }; let elapsed = timer.elapsed(); debug!("SELECT * FROM owners ... {:.3?}", elapsed); Ok(result) diff --git a/src/models/shop.rs b/src/models/shop.rs index ca3c0a3..c5203ca 100644 --- a/src/models/shop.rs +++ b/src/models/shop.rs @@ -67,18 +67,31 @@ impl Model for Shop { async fn list(db: &PgPool, list_params: ListParams) -> Result> { let timer = std::time::Instant::now(); - let result = sqlx::query_as!( - Self, - "SELECT * FROM shops - ORDER BY $1 - LIMIT $2 - OFFSET $3", - list_params.get_order_by(), - list_params.limit.unwrap_or(10), - list_params.offset.unwrap_or(0), - ) - .fetch_all(db) - .await?; + let result = if let Some(order_by) = list_params.get_order_by() { + sqlx::query_as!( + Self, + "SELECT * FROM shops + ORDER BY $1 + LIMIT $2 + OFFSET $3", + order_by, + list_params.limit.unwrap_or(10), + list_params.offset.unwrap_or(0), + ) + .fetch_all(db) + .await? + } else { + sqlx::query_as!( + Self, + "SELECT * FROM shops + LIMIT $1 + OFFSET $2", + list_params.limit.unwrap_or(10), + list_params.offset.unwrap_or(0), + ) + .fetch_all(db) + .await? + }; let elapsed = timer.elapsed(); debug!("SELECT * FROM shops ... {:.3?}", elapsed); Ok(result)