use achubb_database::data::{article::Article, PsqlData}; use askama::Template; use axum::{ extract::{Extension, Path}, response::IntoResponse, routing::{get, Router}, }; use core::panic; use sqlx::PgPool; use std::{collections::HashMap, error::Error}; use super::{root::AppState, HtmlTemplate, NavBar}; pub fn get_router() -> Router { Router::new() .route("/", get(blog)) .route("/:article", get(article)) } async fn blog(state: Extension) -> impl IntoResponse { let db_pool = &state.db; let list: Vec = get_articles_as_links_list(db_pool) .await .expect("couldn't get articles"); let template = BlogTemplate { active_navbar: NavBar::BLOG, article_list: list.join("\n"), }; HtmlTemplate(template) } #[derive(Template)] #[template(path = "blog.html")] struct BlogTemplate { active_navbar: &'static str, article_list: String, } #[derive(Template)] #[template(path = "Article.html")] struct ArticleTemplate { active_navbar: &'static str, next: String, previous: String, content: String, } async fn article( state: Extension, Path(params): Path>, ) -> impl IntoResponse { let db_pool = &state.db; let article_id: &String = params.get("article").unwrap(); let article: Article = match Article::read_by_reference(db_pool, article_id).await { Ok(a) => *a, Err(_) => panic!("Not an article at all!!!!"), }; let template = ArticleTemplate { active_navbar: NavBar::BLOG, content: article.content, previous: match article.previous { Some(a) => a, None => "".to_string(), }, next: match article.next { Some(a) => a, None => "".to_string(), }, }; HtmlTemplate(template) } pub async fn get_articles_as_links_list(pool: &PgPool) -> Result, Box> { let mut articles: Vec
= match Article::read_all(pool).await { Ok(a) => a.iter().map(|x| *x.clone()).collect(), Err(_) => panic!("Not an article at all!!!!"), }; articles.sort_by(|a, b| b.date.cmp(&a.date)); let list: Vec = articles .iter() .map(|article| { format!( "
  • {}
  • ", article.reference, article.title ) }) .collect(); Ok(list) }