* /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
use std::collections::HashMap;
use crate::http::set_json_body;
use db::Neighbor;
use mysql_async::Pool;
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::{Serialize, Deserialize};
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>) {
let url = params.get("url");
let wsurl = params.get("wsurl");
let name = params.get("name");
let desc = params.get("description");
let tags = params.get("tags");
// If any parameter is missing then fail away quickly
if url.is_none() || wsurl.is_none() || name.is_none() || desc.is_none() || tags.is_none() {
*response.status_mut() = StatusCode::BAD_REQUEST;
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);
pub async fn add_neighbor(p: &Pool, response: &mut Response<Body>, body: Body) {
let body: Bytes = to_bytes(body).await.unwrap_or(Bytes::new());
let json: JsonResult<Neighbor> = serde_json::from_slice(&body);
if let Ok(neighbor) = json {
// Before we try adding the new neighbor, make sure there isn't already
// an entry with the same url
if let Ok(row) = db::neighbors::get(p, &neighbor.url).await {
match row.is_some() {
true => *response.status_mut() = StatusCode::CONFLICT,
false => if let Err(e) = db::neighbors::add_neighbor(p, neighbor).await {
eprintln!("{}", e);
}
};
} else {
eprintln!();
*response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
}
}