Files
my-website-v2/backend/public/src/routes/posts.rs

157 lines
5.3 KiB
Rust
Raw Normal View History

2024-12-10 14:06:22 -05:00
use std::collections::HashMap;
use crate::utils::rss;
use crate::{datasources::posts::PostsDatasource, AppState};
2024-12-10 14:06:22 -05:00
use axum::http::{HeaderMap, HeaderValue};
2024-09-25 18:29:12 -04:00
use axum::{
extract::{Path, State},
2024-12-10 14:06:22 -05:00
http::{header, StatusCode},
response::IntoResponse,
2024-09-25 18:29:12 -04:00
routing::get,
Json, Router,
};
use chrono::Utc;
use serde::{Deserialize, Serialize, Serializer};
use sqlx::{Pool, Postgres};
2024-09-25 18:29:12 -04:00
2024-12-10 14:06:22 -05:00
#[derive(sqlx::FromRow, Serialize, Debug, Clone)]
2024-09-25 18:29:12 -04:00
pub struct Post {
pub post_id: i32,
pub author_id: Option<i32>,
pub first_name: Option<String>,
pub last_name: Option<String>,
2024-09-25 18:29:12 -04:00
pub title: String,
pub body: String,
#[serde(serialize_with = "serialize_datetime")]
pub created_at: Option<chrono::DateTime<Utc>>,
}
#[derive(sqlx::FromRow, Serialize, Debug)]
pub struct PostFeaturedVariant {
pub post_id: i32,
pub author_id: Option<i32>,
pub first_name: Option<String>,
pub last_name: Option<String>,
pub title: String,
pub body: String,
#[serde(serialize_with = "serialize_datetime")]
pub created_at: Option<chrono::DateTime<Utc>>,
pub is_featured: Option<bool>,
}
#[derive(Deserialize)]
pub struct PostGetOneParams {
pub id: i32,
2024-09-25 18:29:12 -04:00
}
pub struct PostsRoute;
impl PostsRoute {
pub fn routes(app_state: &AppState) -> Router {
// add more post routes here!
Router::new()
2024-09-25 18:29:12 -04:00
.route("/all", get(PostsRoute::get_all))
.route("/:id", get(PostsRoute::get_one))
.route("/recent", get(PostsRoute::get_recent_posts))
.route("/popular", get(PostsRoute::get_popular_posts))
.route("/hot", get(PostsRoute::get_hot_posts))
.route("/featured", get(PostsRoute::get_featured_posts))
2024-12-10 14:06:22 -05:00
.route("/rss", get(PostsRoute::get_rss_posts))
2024-09-25 18:29:12 -04:00
.with_state(app_state.db.clone())
}
// get all posts
2024-09-25 18:29:12 -04:00
async fn get_all(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_all(&pool).await {
Ok(posts) => Ok(Json(posts)),
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get one post
async fn get_one(
State(pool): State<Pool<Postgres>>,
Path(params): Path<PostGetOneParams>,
) -> impl IntoResponse {
match PostsDatasource::get_one(&pool, params.id).await {
Ok(post) => Ok(Json(post)),
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get recent posts
async fn get_recent_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_recent(&pool).await {
Ok(posts) => Ok(Json(posts)),
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get the top three posts with the highest view count
async fn get_popular_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_popular(&pool).await {
Ok(posts) => Ok(Json(posts)),
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get the top three posts with the most comments
async fn get_hot_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_hot(&pool).await {
Ok(posts) => Ok(Json(posts)),
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get posts that are featured
async fn get_featured_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_featured(&pool).await {
Ok(posts) => Ok(Json(posts)),
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
2024-12-10 14:06:22 -05:00
// 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())
}
}
}
2024-09-25 18:29:12 -04:00
}
pub fn serialize_datetime<S>(
date: &Option<chrono::DateTime<Utc>>,
serializer: S,
) -> Result<S::Ok, S::Error>
2024-09-25 18:29:12 -04:00
where
S: Serializer,
{
serializer.serialize_str(&date.unwrap().to_rfc3339())
}