Begin add PostList routes + 404

This commit is contained in:
Florian RICHER 2023-11-26 17:17:31 +01:00
parent c2df86fc33
commit 224b5d4832
6 changed files with 54 additions and 34 deletions

View file

@ -17,14 +17,13 @@ pub struct Post {
cfg_if::cfg_if! {
if #[cfg(feature = "ssr")] {
impl From<String> for Post {
fn from(content: String) -> Self {
impl Post {
fn from_content(content: String) -> Option<Self> {
use gray_matter::{Matter, engine::YAML};
let matter = Matter::<YAML>::new();
let post_data = matter
.parse_with_struct::<PostMetadata>(&content)
.expect("Unable to parse md frontmatter");
.parse_with_struct::<PostMetadata>(&content)?;
let metadata = post_data.data;
let content = post_data.content;
@ -34,14 +33,25 @@ cfg_if::cfg_if! {
let mut html_output = String::new();
html::push_html(&mut html_output, parser);
Self {
Some(Self {
metadata,
content: html_output,
}
})
}
fn from_path(path: &std::path::Path) -> Option<Self> {
let content = std::fs::read_to_string(path);
let content = match content {
Ok(content) => content,
Err(e) => {
eprintln!("{:?}", e);
return None;
}
};
Self::from_content(content)
}
}
impl Post {
pub fn get_all(folder: &str) -> Result<Vec<Self>, String> {
use std::{path::Path, fs::read_dir};
@ -59,16 +69,9 @@ cfg_if::cfg_if! {
}
};
let content = std::fs::read_to_string(path);
let content = match content {
Ok(content) => content,
Err(e) => {
eprintln!("{:?}", e);
continue;
}
};
let post = Self::from(content);
posts.push(post);
if let Some(post) = Self::from_path(&path) {
posts.push(post);
}
}
Ok(posts)