From 198be70a99ef1cf612cc2ab2f96d0ddb017809b6 Mon Sep 17 00:00:00 2001 From: trotFunky Date: Tue, 30 Jul 2024 23:25:41 +0100 Subject: [PATCH] week: Implement get_last_week Previously, we only needed to get the last week number from the index, to properly redirect to it. However, we will need it in the future in other places. Implement a function that centralizes this database operation. --- src/main.rs | 11 ++--------- src/week.rs | 13 ++++++++++++- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/main.rs b/src/main.rs index 7a8e434..b6e53ff 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ use rocket::response::Redirect; use rocket_dyn_templates::Template; -use rocket_db_pools::{sqlx, sqlx::Row, Connection}; +use rocket_db_pools::Connection; mod auth; @@ -20,14 +20,7 @@ use database::Db; #[get("/")] async fn index(mut db: Connection) -> Redirect { - let current_week: u8 = match sqlx::query("SELECT number FROM Weeks WHERE is_last_week == 1;") - .fetch_one(&mut **db).await { - Ok(v) => v.try_get(0).ok().unwrap_or_else(|| 1), // If error, go back to 1 - Err(error) => { - error!("Error while getting current week : {error:?}"); - 1 - } - }; + let current_week: u8 = week::get_last_week(&mut db).await; Redirect::to(uri!(week::week(week_number = if current_week == 0 {1} else {current_week}))) } diff --git a/src/week.rs b/src/week.rs index 0c56cd7..6148f08 100644 --- a/src/week.rs +++ b/src/week.rs @@ -4,7 +4,7 @@ use rocket::form::Form; use rocket::http::CookieJar; use rocket::response::Redirect; -use rocket_db_pools::{sqlx, Connection}; +use rocket_db_pools::{sqlx, sqlx::Row, Connection}; use rocket_dyn_templates::{context, Template}; use sqlx::{Acquire, Executor}; use crate::{auth, vote}; @@ -13,6 +13,17 @@ use crate::database::Db; use crate::database_records::{DisplayTruth, Player, Truth, Week}; use crate::vote::WeeklyUserVotes; +pub async fn get_last_week(db: &mut Connection) -> u8 { + match sqlx::query("SELECT number FROM Weeks WHERE is_last_week == 1;") + .fetch_one(&mut ***db).await { + Ok(row) => row.try_get(0).ok().unwrap_or_else(|| 1), // If error, go back to 1 + Err(error) => { + error!("Error while getting current week : {error:?}"); + 1 + } + } +} + #[get("/")] pub async fn week(week_number: u8, mut db: Connection, cookies: &CookieJar<'_>) -> Template { let user: User = auth::get_user(&mut db, cookies).await;