use std::borrow::Cow; use mysql_async::{Pool, params}; use mysql_async::prelude::{Queryable}; use mysql_async::error::Error; use hyper::{Response, Body, StatusCode}; use serde_json::Value; use chrono::Utc; use crate::db_types::{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"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(()) } _ => { let e = Cow::from("Required parameter missing"); Err(Error::Other(e)) } } } pub async fn send_message(pool: &Pool, response: &mut Response, params: Value) { /* * @content: expecting string type * @id: expecting the channel id that we're posting data to */ let content_r = params.get("content"); let channel_name_r = params.get("channel"); // auth module guarantees this will be there in the correct form let author = params.get("id") .unwrap().as_u64().unwrap(); 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; } } } }, _ => { *response.status_mut() = StatusCode::BAD_REQUEST; *response.body_mut() = Body::from("content/channel missing from json parameters"); } } }