my-website-v2/backend/task/src/tasks/import_posts.rs

70 lines
2.1 KiB
Rust
Raw Normal View History

use std::fs;
use std::path;
2024-09-22 04:10:29 -04:00
pub 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(),
};
2024-09-22 04:10:29 -04:00
for f in entries {
let file = f.unwrap();
let file_path = file.path();
if file_path.is_file() {
let file_name = file.file_name();
let file_name_final = &file_name.to_str().unwrap();
2024-09-22 04:10:29 -04:00
let exists = sqlx::query_as::<_, FilenameExists>(
"SELECT EXISTS(SELECT 1 FROM posts WHERE filename = $1)",
)
.bind(file_name_final)
2024-09-22 04:10:29 -04:00
.fetch_one(pool)
.await
.unwrap()
.filename;
if !exists.is_empty() {
println!(
"File does not exist! Inserting: {:?}",
file_path.file_name()
);
let file_md_contents = process_read_file(file_path, &options);
let content = markdown::to_html(&file_md_contents);
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(content)
.bind(file_name_final)
.bind(1)
.fetch_one(pool)
.await
.unwrap();
2024-09-22 04:10:29 -04:00
}
}
}
}
fn process_read_file<P: AsRef<path::Path>>(path: P, md_opts: &MarkdownOptions) -> String {
let file_contents = fs::read_to_string(path).unwrap();
markdown::to_html(file_contents.as_str())
}
2024-09-22 04:10:29 -04:00
#[derive(Debug, sqlx::FromRow)]
struct FilenameExists {
filename: String,
}
#[derive(Debug, sqlx::FromRow)]
struct InsertPosts {
title: String,
body: String,
filename: String,
author_id: i32,
}
struct MarkdownOptions {
options: markdown::Constructs,
2024-09-22 04:10:29 -04:00
}