diff --git a/json-api/src/meta.rs b/json-api/src/meta.rs index 96f1d6e..54571c5 100644 --- a/json-api/src/meta.rs +++ b/json-api/src/meta.rs @@ -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) { } -pub async fn add_neighbor(p: &Pool, response: &mut Response, params: HashMap) { - 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) { + let body: Bytes = to_bytes(body).await.unwrap_or(Bytes::new()); + let json: JsonResult = 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; } }