82 lines
2.3 KiB
Rust
Raw Normal View History

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<chrono::DateTime<Utc>>,
}
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))
2024-09-25 18:29:12 -04:00
.with_state(app_state.db.clone())
}
async fn get_post_comments(
State(pool): State<Pool<Postgres>>,
Path(params): Path<CommentPathParams>,
) -> 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())),
}
}
2024-09-25 18:29:12 -04:00
//
async fn insert_comment(
State(pool): State<Pool<Postgres>>,
Json(input): Json<CommentInputPayload>,
) -> 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<Pool<Postgres>>,
Json(pagination): Json<Pagination>,
) -> 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())),
}
}
}