Debug printing in new_comment route
This commit is contained in:
parent
a0a165d66b
commit
f1c03ffa80
1 changed files with 82 additions and 0 deletions
82
server/src/routes/comment.rs
Normal file
82
server/src/routes/comment.rs
Normal file
|
@ -0,0 +1,82 @@
|
|||
use crate::db::{db_get_comments, db_new_comment};
|
||||
use crate::jwt::Authentication;
|
||||
use crate::types::{CommentQueryParams, NewComment};
|
||||
use crate::ServerState;
|
||||
|
||||
use actix_web::get;
|
||||
use actix_web::web::{Data, Query};
|
||||
use actix_web::{post, web::Json, HttpResponse, Responder, Result};
|
||||
use log::info;
|
||||
|
||||
#[get("/comments")]
|
||||
pub async fn get_comments(
|
||||
comment_filter: Query<CommentQueryParams>,
|
||||
state: Data<ServerState>,
|
||||
) -> Result<impl Responder> {
|
||||
let post_id = comment_filter.post_id;
|
||||
let limit = comment_filter.limit.unwrap_or(10);
|
||||
let offset = comment_filter.offset.unwrap_or(0);
|
||||
|
||||
info!(
|
||||
"Getting comments for post {} with limit {} and offset {}",
|
||||
post_id, limit, offset
|
||||
);
|
||||
|
||||
let comments = db_get_comments(&state.pool, post_id, limit, offset).await;
|
||||
|
||||
Ok(HttpResponse::Ok().json(comments))
|
||||
}
|
||||
|
||||
#[post("/comments")]
|
||||
pub async fn new_comment(
|
||||
data: Json<NewComment>,
|
||||
state: Data<ServerState>,
|
||||
auth: Data<Authentication>,
|
||||
) -> Result<impl Responder> {
|
||||
let user_claims = auth.decode(&data.user_token);
|
||||
|
||||
// Bail if the token is invalid
|
||||
if let Err(e) = user_claims {
|
||||
info!("Error validating token: {}", e);
|
||||
return Ok(HttpResponse::BadRequest().json("Error"));
|
||||
}
|
||||
|
||||
let claims = user_claims.unwrap();
|
||||
|
||||
let content = data.content.clone();
|
||||
let username = claims.sub.clone();
|
||||
|
||||
// This one is avoidable if we just store the user id in the token
|
||||
let userid = sqlx::query!("SELECT id FROM users WHERE username = $1", username)
|
||||
.fetch_one(&state.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.id;
|
||||
|
||||
info!(
|
||||
"User {:?}, with id {:?} is creating a new comment",
|
||||
&claims.sub, userid
|
||||
);
|
||||
|
||||
info!("Creating a new comment {:?}", &data);
|
||||
|
||||
let success = db_new_comment(
|
||||
&state.pool,
|
||||
data.parent_post_id,
|
||||
data.parent_comment_id,
|
||||
userid,
|
||||
&content,
|
||||
)
|
||||
.await;
|
||||
|
||||
match success {
|
||||
true => {
|
||||
info!("User {:?} created a new comment", &claims.sub);
|
||||
Ok(HttpResponse::Ok().json("Successfully created comment"))
|
||||
}
|
||||
false => {
|
||||
info!("User {:?} failed to create a new comment", &claims.sub);
|
||||
Ok(HttpResponse::BadRequest().json("Failed to create comment"))
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue