diff --git a/server/src/messages.rs b/server/src/messages.rs index 8bba9fb..399f3b4 100644 --- a/server/src/messages.rs +++ b/server/src/messages.rs @@ -10,17 +10,21 @@ use chrono::Utc; use crate::db_types::{UBigInt}; -pub async fn insert_message_table(pool: &Pool, content: &Value, channel_name: &Value, author_id: UBigInt) +pub async fn insert_message(pool: &Pool, content: &Value, channel_name: &Value, author_id: UBigInt) -> Result<(), Error>{ match (content.as_str(), channel_name.as_str()) { (Some(content), Some(channel)) => { let conn = pool.get_conn().await?; let time = Utc::now().timestamp(); - conn.prep_exec(r"", params!{ - "time" => time, - "content" => content, - "author" => author_id, - "channel" => channel + conn.prep_exec( + r"INSERT INTO messages + (time, content, author_id, channel_name) + VALUES(:time, :content, :author, :channel)", + params!{ + "time" => time, + "content" => content, + "author" => author_id, + "channel" => channel }).await?; Ok(()) } @@ -37,16 +41,32 @@ pub async fn send_message(pool: &Pool, response: &mut Response, params: Va * @id: expecting the channel id that we're posting data to */ let content_r = params.get("content"); - let channel_id_r = params.get("channel"); + let channel_name_r = params.get("channel"); // auth module guarantees this will be there in the correct form let author = params.get("userid") .unwrap().as_u64().unwrap(); - match (content_r, channel_id_r) { - (Some(content), Some(channel_id)) => { - // insert the new message into our db - if let Ok(_db_result) = insert_message_table(pool, content, channel_id, author).await { - *response.status_mut() = StatusCode::OK; + match (content_r, channel_name_r) { + (Some(content), Some(channel_name)) => { + match insert_message(pool, content, channel_name, author).await { + Ok(_) => *response.status_mut() = StatusCode::OK, + Err(err) => { + use mysql_async::error::Error::{Server}; + println!("\tDB Error::send_message: {:?}", err); + // doing this to avoid client confusion as some input does cause sql errors + if let Server(se) = err { + if se.code == 1452 { + *response.status_mut() = StatusCode::BAD_REQUEST; + *response.body_mut() = Body::from(format!("{} does not exist", channel_name)); + } + else { + *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; + } + } + else { + *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; + } + } } }, _ => {