added rss generator

This commit is contained in:
2024-12-10 14:06:22 -05:00
parent ae86f86339
commit 637f0b47dd
6 changed files with 190 additions and 3 deletions

View File

@ -1,7 +1,11 @@
use std::collections::HashMap;
use crate::utils::rss;
use crate::{datasources::posts::PostsDatasource, AppState};
use axum::http::{HeaderMap, HeaderValue};
use axum::{
extract::{Path, State},
http::StatusCode,
http::{header, StatusCode},
response::IntoResponse,
routing::get,
Json, Router,
@ -10,7 +14,7 @@ use chrono::Utc;
use serde::{Deserialize, Serialize, Serializer};
use sqlx::{Pool, Postgres};
#[derive(sqlx::FromRow, Serialize, Debug)]
#[derive(sqlx::FromRow, Serialize, Debug, Clone)]
pub struct Post {
pub post_id: i32,
pub author_id: Option<i32>,
@ -51,6 +55,7 @@ impl PostsRoute {
.route("/popular", get(PostsRoute::get_popular_posts))
.route("/hot", get(PostsRoute::get_hot_posts))
.route("/featured", get(PostsRoute::get_featured_posts))
.route("/rss", get(PostsRoute::get_rss_posts))
.with_state(app_state.db.clone())
}
@ -104,6 +109,40 @@ impl PostsRoute {
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get rss posts
async fn get_rss_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_all(&pool).await {
Ok(posts) => {
let web_url = std::env::var("BASE_URI_WEB").expect("No environment variable found");
let mapped_posts: HashMap<String, Post> = posts
.into_iter()
.map(|post| (post.post_id.to_string(), post))
.collect();
let xml: String = rss::generate_rss(
"Wyatt's blog",
"Wyatt and friends",
web_url.as_str(),
&mapped_posts,
);
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_str(r#"attachment; filename="posts.xml""#).unwrap(),
);
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/xml"),
);
(headers, xml)
}
Err(e) => {
let mut headers = HeaderMap::new();
headers.insert("Content-Type", HeaderValue::from_static("text/plain"));
(headers, e.to_string())
}
}
}
}
pub fn serialize_datetime<S>(