+ updated parsing funcs to take advantage of serde_json

+removed unused code segmments
+added helper function to pull string from Option<i64> for serde_json
*exposing Channel struct to other modules
This commit is contained in:
shockrah 2020-07-04 19:37:42 -07:00
parent e8e1a13d6d
commit cb3aec0696

View File

@ -1,12 +1,14 @@
use std::collections::HashMap;
use std::borrow::Cow;
use hyper::{StatusCode, Response, Body};
use hyper::header::HeaderValue;
use mysql_async::{Conn, Pool};
use mysql_async::error::Error;
use mysql_async::prelude::{params, Queryable};
use serde_json::Value;
enum ChannelType {
Voice,
Text,
@ -30,10 +32,24 @@ impl ChannelType {
}
}
// whole ass function exists because serde_json is a walking pos
fn from_i64_opt(x: Option<i64>) -> ChannelType {
if let Some(i) = x {
match i {
1 => ChannelType::Voice,
2 => ChannelType::Text,
_ => ChannelType::Undefined
}
}
else {
ChannelType::Undefined
}
}
}
// Primary way of interpretting sql data on our channels table
struct Channel {
pub struct Channel {
id: i32,
name: String,
description: String,
@ -130,29 +146,21 @@ pub async fn list_channels(pool: &Pool, response: &mut Response<Body>) {
}
}
fn parse_insert_channel_params(name: Option<&&str>, kind: Option<&&str>, desc: Option<&&str>) ->
fn parse_insert_channel_params(name_r: Option<&Value>, kind_r: Option<&Value>, desc_r: Option<&Value>) ->
Result<InsertableChannel, Error> {
match (name, kind) {
match (name_r, kind_r) {
(Some(name), Some(kind)) => {
let mut channel = InsertableChannel {
name: name.to_string(),
kind: ChannelType::Undefined,
description: String::new()
let desc: String = match desc_r {
Some(d) => d.as_str().unwrap().to_string(), // if this fails burn the server
None => "".into()
};
match kind.parse::<i32>() {
Ok(val) => {
channel.kind = ChannelType::from_i32(val);
if let Some(d) = desc {
channel.description = d.to_string();
}
Ok(channel)
},
Err(_) => {
let x = Cow::from("Parse error with kind parameter");
Err(Error::Other(x))
}
}
let channel = InsertableChannel {
name: name.to_string(),
kind: ChannelType::from_i64_opt(kind.as_i64()),
description: desc
};
Ok(channel)
}
_ => {
let x = Cow::from("Missing required parameters");
@ -172,7 +180,7 @@ async fn insert_channel(pool: &Pool, channel: InsertableChannel) -> Result<(), E
Ok(())
}
pub async fn create_channel(pool: &Pool, response: &mut Response<Body>, params: &HashMap<&str, &str>) {
pub async fn create_channel(pool: &Pool, response: &mut Response<Body>, params: Value) {
/*
* Create a channel base on a few parameters that may or may not be there
*/