use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct PageData { pub title: String, pub lang: String, pub description: String, pub slug: String, pub html_body: String, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct WebPage { pub page_data: PageData, pub html_doc: String, } impl PageData { pub fn to_web_page(&self) -> WebPage { WebPage { page_data: self.clone(), html_doc: self.html_body.clone(), // TMP } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct PagesTree { pub page_data: PageData, pub sub_pages: Option<Vec<PagesTree>>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct WebSite { pages_tree: PagesTree, pages_index_by_url: HashMap<String, WebPage>, } impl WebSite { pub fn new(pages_tree: PagesTree) -> Self { let mut pages_index_by_url = HashMap::new(); WebSite::create_index_by_url(&mut pages_index_by_url, &pages_tree, String::new()); WebSite { pages_tree, pages_index_by_url, } } fn create_index_by_url( index: &mut HashMap<String, WebPage>, pages_tree: &PagesTree, from_url: String, ) { let page_data = pages_tree.page_data.clone(); let url = format!("{}{}/", from_url, page_data.slug); index.insert(url.to_owned(), page_data.to_web_page()); if let Some(sub_pages) = &pages_tree.sub_pages { for pt in sub_pages { WebSite::create_index_by_url(index, pt, url.to_owned()); } } } pub fn get_page_by_url(&self, url: &String) -> Option<&WebPage> { self.pages_index_by_url.get(url) } } #[cfg(test)] mod test_website { use super::*; const JSON_TEMPLATE: &'static str = " { \"page_data\": { \"title\": \"Test Website\", \"slug\": \"\", \"lang\": \"en\", \"description\": \"A test website\", \"html_body\": \"<h1>Test Website</h1>\" }, \"sub_pages\": [ { \"page_data\": { \"title\": \"A sub page\", \"slug\": \"subpage\", \"lang\": \"en\", \"description\": \"A sub page of the testing web site\", \"html_body\": \"<h1>A sub page</h1>\" }, \"sub_pages\": [ { \"page_data\": { \"title\": \"Another page\", \"lang\": \"en\", \"slug\": \"otherpage\", \"description\": \"Another testing page\", \"html_body\": \"<h1>Another page</h1>\" } } ] } ] } "; #[test] fn test_index_pages_by_slug() { let pages_tree: PagesTree = serde_json::from_str(JSON_TEMPLATE).unwrap(); let website = WebSite::new(pages_tree); let root_page = website.get_page_by_url(&"/".to_string()); assert!(root_page.is_some()); let root_page = root_page.unwrap(); assert_eq!(root_page.page_data.html_body, "<h1>Test Website</h1>"); let sub_page = website.get_page_by_url(&"/subpage/".to_string()); assert!(sub_page.is_some()); let sub_page = sub_page.unwrap(); assert_eq!(sub_page.page_data.html_body, "<h1>A sub page</h1>"); } }