use super::posts::serialize_datetime; use crate::{datasources::comments::CommentsDatasource, AppState}; use axum::{ extract::{Path, State}, http::StatusCode, response::IntoResponse, routing::{get, post}, Json, }; use chrono::Utc; use serde::{Deserialize, Serialize}; use sqlx::{Pool, Postgres}; #[derive(Deserialize, Debug)] pub struct CommentInputPayload { pub name: String, pub body: String, pub post_id: i32, } #[derive(Deserialize)] pub struct CommentPathParams { id: i32, } #[derive(Deserialize)] pub struct Pagination { pub page_number: i64, pub page_size: i64, } #[derive(sqlx::FromRow, Serialize, Debug)] pub struct Comment { pub comment_id: i32, pub name: String, pub body: String, #[serde(serialize_with = "serialize_datetime")] pub created_at: Option>, } pub struct CommentsRoute; impl CommentsRoute { pub fn routes(app_state: &AppState) -> axum::Router { // add more comment routes here! axum::Router::new() .route("/post/:id", get(CommentsRoute::get_post_comments)) .route("/add", post(CommentsRoute::insert_comment)) .route("/index", get(CommentsRoute::get_comments_index)) .with_state(app_state.db.clone()) } async fn get_post_comments( State(pool): State>, Path(params): Path, ) -> impl IntoResponse { match CommentsDatasource::get_posts_comments(&pool, params.id).await { Ok(c) => Ok(Json(c)), Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())), } } // async fn insert_comment( State(pool): State>, Json(input): Json, ) -> impl IntoResponse { match CommentsDatasource::insert_comment(&pool, input).await { Ok(c) => Ok((StatusCode::CREATED, Json(c))), Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())), } } async fn get_comments_index( State(pool): State>, Json(pagination): Json, ) -> impl IntoResponse { match CommentsDatasource::get_index_comments(&pool, pagination).await { Ok(c) => Ok(Json(c)), Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())), } } }