wip: added get post comments, working insert comment to post

This commit is contained in:
2024-09-27 23:17:33 -04:00
parent c303e6aaee
commit 8128459b4e
4 changed files with 69 additions and 30 deletions

View File

@ -1,17 +1,35 @@
use super::posts::serialize_datetime;
use crate::{datasources::comments::CommentsDatasource, AppState};
use axum::{
extract::{Form, State},
extract::{Form, Path, State},
http::StatusCode,
response::IntoResponse,
routing::{get, post},
Json,
};
use serde::Deserialize;
use sqlx::PgPool;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use sqlx::{Pool, Postgres};
#[derive(Deserialize, Debug)]
pub struct CommentInput {
name: String,
body: String,
post_id: i32,
pub struct CommentInputPayload {
pub name: String,
pub body: String,
pub post_id: i32,
}
#[derive(Deserialize)]
pub struct CommentPathParams {
id: i32,
}
#[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;
@ -19,21 +37,28 @@ 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("/post/:id", get(CommentsRoute::get_post_comments))
.route("/add", post(CommentsRoute::insert_comment))
.with_state(app_state.db.clone())
}
// async fn get_post_comments(State(pool): State<PgPool>) -> Json<()> {
// let results = CommentsDatasource::get_posts_comments(pool).await;
// Json {}
// }
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())),
}
}
//
// async fn insert_comment(
// State(pool): State<PgPool>,
// Form(comment_input): Form<CommentInput>,
// ) -> bool {
// let results = CommentsDatasource::insert_comment(pool, comment_input).await;
// true
// }
async fn insert_comment(
State(pool): State<Pool<Postgres>>,
Json(comment_input): Json<CommentInputPayload>,
) -> impl IntoResponse {
match CommentsDatasource::insert_comment(&pool, comment_input).await {
Ok(c) => Ok((StatusCode::CREATED, Json(c))),
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
}

View File

@ -74,7 +74,7 @@ impl PostsRoute {
}
}
fn serialize_datetime<S>(
pub fn serialize_datetime<S>(
date: &Option<chrono::DateTime<Utc>>,
serializer: S,
) -> Result<S::Ok, S::Error>