Modularize, Model trait, list_owners

This commit is contained in:
2020-07-18 17:46:33 -04:00
parent 6b1f31f246
commit 9ec7fc1518
10 changed files with 462 additions and 389 deletions

76
src/handlers/mod.rs Normal file
View File

@@ -0,0 +1,76 @@
use ipnetwork::IpNetwork;
use std::net::SocketAddr;
use warp::http::StatusCode;
use warp::reply::{json, with_header, with_status};
use warp::{Rejection, Reply};
use super::models::{ListParams, Model, Owner, Shop};
use super::problem::reject_anyhow;
use super::Environment;
pub async fn get_shop(id: i32, env: Environment) -> Result<impl Reply, Rejection> {
let shop = Shop::get(&env.db, id).await.map_err(reject_anyhow)?;
let reply = json(&shop);
let reply = with_status(reply, StatusCode::OK);
Ok(reply)
}
pub async fn list_shops(
list_params: ListParams,
env: Environment,
) -> Result<impl Reply, Rejection> {
let shops = Shop::list(&env.db, list_params)
.await
.map_err(reject_anyhow)?;
let reply = json(&shops);
let reply = with_status(reply, StatusCode::OK);
Ok(reply)
}
pub async fn create_shop(shop: Shop, env: Environment) -> Result<impl Reply, Rejection> {
let saved_shop = shop.save(&env.db).await.map_err(reject_anyhow)?;
let url = saved_shop.url(&env.api_url).map_err(reject_anyhow)?;
let reply = json(&saved_shop);
let reply = with_header(reply, "Location", url.as_str());
let reply = with_status(reply, StatusCode::CREATED);
Ok(reply)
}
pub async fn get_owner(id: i32, env: Environment) -> Result<impl Reply, Rejection> {
let owner = Owner::get(&env.db, id).await.map_err(reject_anyhow)?;
let reply = json(&owner);
let reply = with_status(reply, StatusCode::OK);
Ok(reply)
}
pub async fn list_owners(
list_params: ListParams,
env: Environment,
) -> Result<impl Reply, Rejection> {
let owners = Owner::list(&env.db, list_params)
.await
.map_err(reject_anyhow)?;
let reply = json(&owners);
let reply = with_status(reply, StatusCode::OK);
Ok(reply)
}
pub async fn create_owner(
owner: Owner,
remote_addr: Option<SocketAddr>,
env: Environment,
) -> Result<impl Reply, Rejection> {
let owner_with_ip = match remote_addr {
Some(addr) => Owner {
ip_address: Some(IpNetwork::from(addr.ip())),
..owner
},
None => owner,
};
let saved_owner = owner_with_ip.save(&env.db).await.map_err(reject_anyhow)?;
let url = saved_owner.url(&env.api_url).map_err(reject_anyhow)?;
let reply = json(&saved_owner);
let reply = with_header(reply, "Location", url.as_str());
let reply = with_status(reply, StatusCode::CREATED);
Ok(reply)
}