From cb3aec0696c243f3cfc1cf4d9db13b6e8a7ecdb0 Mon Sep 17 00:00:00 2001 From: shockrah Date: Sat, 4 Jul 2020 19:37:42 -0700 Subject: [PATCH] + updated parsing funcs to take advantage of serde_json +removed unused code segmments +added helper function to pull string from Option for serde_json *exposing Channel struct to other modules --- server/src/channels.rs | 52 ++++++++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 22 deletions(-) diff --git a/server/src/channels.rs b/server/src/channels.rs index 6226891..ab37cc0 100644 --- a/server/src/channels.rs +++ b/server/src/channels.rs @@ -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) -> 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) { } } -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 { - 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::() { - 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, params: &HashMap<&str, &str>) { +pub async fn create_channel(pool: &Pool, response: &mut Response, params: Value) { /* * Create a channel base on a few parameters that may or may not be there */