implemented front matter parser, created task log abstraction fuctions

This commit is contained in:
2024-10-04 07:21:10 -04:00
parent 59d8273498
commit 3c78ed5ae3
4 changed files with 67 additions and 19 deletions

View File

@ -1,9 +1,20 @@
use std::fs;
use std::path;
pub async fn import_posts(dir_path: &str, pool: &sqlx::Pool<sqlx::Postgres>) {
use serde::Deserialize;
use serde::Deserializer;
pub fn register<'a>(pool: &'a sqlx::Pool<sqlx::Postgres>) {
let p = pool.clone();
tokio::spawn(async move {
import_posts("/app", &p).await;
});
}
async fn import_posts(dir_path: &str, pool: &sqlx::Pool<sqlx::Postgres>) {
println!("hello from import_posts");
let entries = fs::read_dir(dir_path).unwrap();
let options = MarkdownOptions {
options: markdown::Constructs::gfm(),
};
@ -30,11 +41,13 @@ pub async fn import_posts(dir_path: &str, pool: &sqlx::Pool<sqlx::Postgres>) {
);
let file_md_contents = process_read_file(file_path, &options);
let content = markdown::to_html(&file_md_contents);
let metadata = crate::utils::front_matter::YamlFrontMatter::parse::<MarkdownMetadata>(&content).unwrap();
let title = metadata.metadata.title;
sqlx::query_as::<_, InsertPosts>(
"INSERT INTO posts (title, body, filename, author_id) VALUES ($1, $2, $3, $4) RETURNING (title, body, filename, author_id)",
)
.bind(String::from("Hello world from Postgres!"))
.bind(title)
.bind(content)
.bind(file_name_final)
.bind(1)
@ -67,3 +80,22 @@ struct InsertPosts {
struct MarkdownOptions {
options: markdown::Constructs,
}
#[derive(Deserialize)]
struct MarkdownMetadata {
layout: String,
title: String,
#[serde(deserialize_with = "deserialize_datetime")]
date: chrono::DateTime<chrono::Utc>,
published: bool,
}
fn deserialize_datetime<'de, D>(deserializer: D) -> Result<chrono::DateTime<chrono::Utc>, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
chrono::DateTime::parse_from_rfc3339(&s)
.map(|dt| dt.with_timezone(&chrono::Utc))
.map_err(serde::de::Error::custom)
}