* /neighbor/add handler now uses body for neighbor structure data

This chage is basically required due to the ridiculuous number of parameters that needed to be passed.
Also more POC for showing how serde_json's result type can be used to safely parse http bodies
This commit is contained in:
shockrah 2021-05-11 17:23:15 -07:00
parent 666894af0e
commit 1ca17ec6e0

View File

@ -1,9 +1,12 @@
// Basic handler for getting meta data about the server // Basic handler for getting meta data about the server
use std::collections::HashMap; use std::collections::HashMap;
use crate::http::set_json_body; use crate::http::set_json_body;
use db::Neighbor;
use mysql_async::Pool; use mysql_async::Pool;
use hyper::{Response, Body, StatusCode}; use hyper::{Response, Body, StatusCode};
use hyper::body::to_bytes;
use hyper::body::Bytes;
use serde_json::{json, to_string, Result as JsonResult}; use serde_json::{json, to_string, Result as JsonResult};
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use lazy_static::lazy_static; use lazy_static::lazy_static;
@ -69,28 +72,21 @@ pub async fn server_neighbors(p: &Pool, response: &mut Response<Body>) {
} }
pub async fn add_neighbor(p: &Pool, response: &mut Response<Body>, params: HashMap<String, String>) { pub async fn add_neighbor(p: &Pool, response: &mut Response<Body>, body: Body) {
let url = params.get("url"); let body: Bytes = to_bytes(body).await.unwrap_or(Bytes::new());
let wsurl = params.get("wsurl"); let json: JsonResult<Neighbor> = serde_json::from_slice(&body);
let name = params.get("name"); if let Ok(neighbor) = json {
let desc = params.get("description"); // Before we try adding the new neighbor, make sure there isn't already
let tags = params.get("tags"); // an entry with the same url
if let Ok(row) = db::neighbors::get(p, &neighbor.url).await {
// If any parameter is missing then fail away quickly match row.is_some() {
if url.is_none() || wsurl.is_none() || name.is_none() || desc.is_none() || tags.is_none() { true => *response.status_mut() = StatusCode::CONFLICT,
*response.status_mut() = StatusCode::BAD_REQUEST; false => if let Err(e) = db::neighbors::add_neighbor(p, neighbor).await {
return;
}
// Safe unwrap because of the check above
let url = url.unwrap();
let wsurl = wsurl.unwrap();
let name = name.unwrap();
let desc = desc.unwrap();
let tags = tags.unwrap();
match db::neighbors::add_neighbor(p, url, wsurl, name, desc, tags).await {
Ok(()) => {},
Err(e) => {
eprintln!("{}", e); eprintln!("{}", e);
}
};
} else {
eprintln!();
*response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
} }
} }