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.
This commit is contained in:
parent
f7efe0b66c
commit
198be70a99
2 changed files with 14 additions and 10 deletions
11
src/main.rs
11
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<Db>) -> 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})))
|
||||
}
|
||||
|
|
13
src/week.rs
13
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<Db>) -> 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("/<week_number>")]
|
||||
pub async fn week(week_number: u8, mut db: Connection<Db>, cookies: &CookieJar<'_>) -> Template {
|
||||
let user: User = auth::get_user(&mut db, cookies).await;
|
||||
|
|
Loading…
Add table
Reference in a new issue