moves API logic inside its own module

This commit is contained in:
2019-10-17 12:56:07 +02:00
parent 3cc45397da
commit 185e1403e3
6 changed files with 252 additions and 196 deletions

View File

@@ -19,8 +19,8 @@ mod schema;
pub use models::{ pub use models::{
claim::{Claim, Claims}, claim::{Claim, Claims},
item::{Item, LootManager}, item::{Item, LootManager, Inventory},
player::{Player, Players, Wealth}, player::{Player, Wealth, Players, AsPlayer},
}; };
/// The connection used /// The connection used
@@ -29,184 +29,66 @@ pub type DbConnection = SqliteConnection;
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>; pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
/// The result of a query on DB /// The result of a query on DB
pub type QueryResult<T> = Result<T, diesel::result::Error>; pub type QueryResult<T> = Result<T, diesel::result::Error>;
/// The result of an action provided by DbApi
pub type ActionResult<R> = Result<R, diesel::result::Error>;
#[derive(Serialize, Deserialize, Debug)] /// Sets up a connection pool and returns it.
pub enum Update { /// Uses the DATABASE_URL environment variable (must be set)
Wealth(Wealth), pub fn create_pool() -> Pool {
ItemAdded(Item), let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
ItemRemoved(Item), dbg!(&connspec);
ClaimAdded(Claim), let manager = ConnectionManager::<DbConnection>::new(connspec);
ClaimRemoved(Claim), r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.")
} }
#[derive(Serialize, Deserialize, Debug)]
pub enum Value {
Item(Item),
Claim(Claim),
ItemList(Vec<Item>),
ClaimList(Vec<Claim>),
PlayerList(Vec<Player>),
}
#[derive(Serialize, Deserialize, Debug, Default)] /// Sells a single item inside a transaction
pub struct ApiResponse { ///
pub value: Option<Value>, // The value requested, if any /// # Returns
pub notify: Option<String>, // A text to notify user, if relevant /// The deleted entity and the updated Wealth (as a difference from previous value)
pub updates: Option<Vec<Update>>, // A list of updates, if any pub fn sell_item_transaction(
pub errors: Option<String>, // A text describing errors, if any
}
impl ApiResponse {
fn push_update(&mut self, update: Update) {
if let Some(v) = self.updates.as_mut() {
v.push(update);
} else {
self.updates = Some(vec![update]);
}
}
fn push_error<S: Into<String>>(&mut self, error: S) {
if let Some(errors) = self.errors.as_mut() {
*errors = format!("{}\n{}", errors, error.into());
} else {
self.errors = Some(error.into())
}
}
fn set_value(&mut self, value: Value) {
self.value = Some(value);
}
fn notifiy<S: Into<String>>(&mut self, text: S) {
self.notify = Some(text.into());
}
}
pub enum ApiError {
DieselError(diesel::result::Error),
InvalidAction(String),
}
pub enum ApiActions {
FetchPlayers,
FetchInventory,
// Player actions
FetchLoot(i32),
UpdateWealth(i32, f32),
BuyItems(i32, Vec<(i32, Option<f32>)>),
SellItems(i32, Vec<(i32, Option<f32>)>),
ClaimItem(i32, i32),
UnclaimItem(i32, i32),
// Group actions
AddLoot(Vec<Item>),
}
pub enum AdminActions {
AddPlayer(String, f32),
//AddInventoryItem(pub String, pub i32),
ResolveClaims,
//SetClaimsTimeout(pub i32),
}
pub fn execute(
conn: &DbConnection, conn: &DbConnection,
query: ApiActions, id: i32,
) -> Result<ApiResponse, diesel::result::Error> { loot_id: i32,
let mut response = ApiResponse::default(); price_mod: Option<f32>,
match query { ) -> QueryResult<(Item, Wealth)> {
ApiActions::FetchPlayers => { conn.transaction(|| {
response.set_value(Value::PlayerList(models::player::Players(conn).all()?)); let deleted = LootManager(conn, id)
.remove(loot_id)?;
let mut sell_value =
deleted.base_price as f32 / 2.0;
if let Some(modifier) = price_mod {
sell_value *= modifier;
} }
ApiActions::FetchInventory => { let wealth = AsPlayer(conn, id)
response.set_value(Value::ItemList(models::item::Inventory(conn).all()?)); .update_wealth(sell_value)?;
} Ok((deleted, wealth))
ApiActions::FetchLoot(id) => { })
response.set_value(Value::ItemList(models::item::LootManager(conn, id).all()?)); }
}
ApiActions::UpdateWealth(id, amount) => { /// Buys a single item, copied from inventory.
response.push_update(Update::Wealth( /// Runs inside a transaction
models::player::AsPlayer(conn, id).update_wealth(amount)?, ///
)); /// # Returns
} /// The created entity and the updated Wealth (as a difference from previous value)
ApiActions::BuyItems(id, params) => { pub fn buy_item_from_inventory(
let mut cumulated_diff: Vec<Wealth> = Vec::with_capacity(params.len()); conn: &DbConnection,
let mut added_items: Vec<models::Item> = Vec::with_capacity(params.len()); id: i32,
for (item_id, price_mod) in params.into_iter() { item_id: i32,
// Use a transaction to avoid incoherant state in case of error price_mod: Option<f32>,
if let Ok((item, diff)) = conn.transaction(|| { ) -> QueryResult<(Item, Wealth)> {
// Find item in inventory conn.transaction(|| {
let item = models::item::Inventory(conn).find(item_id)?; // Find item in inventory
let new_item = models::item::LootManager(conn, id).add_from(&item)?; let item = Inventory(conn).find(item_id)?;
let sell_price = match price_mod { let new_item = LootManager(conn, id).add_from(&item)?;
Some(modifier) => item.base_price as f32 * modifier, let sell_price = match price_mod {
None => item.base_price as f32, Some(modifier) => item.base_price as f32 * modifier,
}; None => item.base_price as f32,
models::player::AsPlayer(conn, id) };
.update_wealth(-sell_price) AsPlayer(conn, id)
.map(|diff| (new_item, diff)) .update_wealth(-sell_price)
}) { .map(|diff| (new_item, diff))
cumulated_diff.push(diff); })
response.push_update(Update::ItemAdded(item));
} else {
response.push_error(format!("Error adding {}", item_id));
}
}
let all_diff = cumulated_diff
.into_iter()
.fold(Wealth::from_gp(0.0), |sum, diff| Wealth {
cp: sum.cp + diff.cp,
sp: sum.sp + diff.sp,
gp: sum.gp + diff.gp,
pp: sum.pp + diff.pp,
});
response.push_update(Update::Wealth(all_diff));
}
ApiActions::SellItems(id, params) => {
let mut all_results: Vec<Wealth> = Vec::with_capacity(params.len());
for (loot_id, price_mod) in params.into_iter() {
let res = conn.transaction(|| {
let deleted = models::item::LootManager(conn, id).remove(loot_id)?;
let mut sell_value = deleted.base_price as f32 / 2.0;
if let Some(modifier) = price_mod {
sell_value *= modifier;
}
models::player::AsPlayer(conn, id)
.update_wealth(sell_value)
.map(|diff| (deleted, diff))
});
if let Ok((deleted, diff)) = res {
all_results.push(diff);
response.push_update(Update::ItemRemoved(deleted));
} else {
response.push_error(format!("Error selling {}", loot_id));
}
}
let wealth = all_results
.into_iter()
.fold(Wealth::from_gp(0.0), |sum, diff| Wealth {
cp: sum.cp + diff.cp,
sp: sum.sp + diff.sp,
gp: sum.gp + diff.gp,
pp: sum.pp + diff.pp,
});
response.push_update(Update::Wealth(wealth));
}
ApiActions::ClaimItem(id, item) => {
response.push_update(Update::ClaimAdded(
models::claim::Claims(conn).add(id, item)?,
));
}
ApiActions::UnclaimItem(id, item) => {
response.push_update(Update::ClaimRemoved(
models::claim::Claims(conn).remove(id, item)?,
));
}
// Group actions
ApiActions::AddLoot(items) => {}
}
Ok(response)
} }
/// Fetch all existing claims /// Fetch all existing claims
@@ -238,16 +120,6 @@ pub fn resolve_claims(conn: &DbConnection) -> QueryResult<()> {
Ok(()) Ok(())
} }
/// Sets up a connection pool and returns it.
/// Uses the DATABASE_URL environment variable (must be set)
pub fn create_pool() -> Pool {
let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
dbg!(&connspec);
let manager = ConnectionManager::<DbConnection>::new(connspec);
r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.")
}
#[cfg(none)] #[cfg(none)]
mod tests_old { mod tests_old {

View File

@@ -132,6 +132,21 @@ impl Wealth {
} }
} }
use std::ops::Add;
impl Add for Wealth {
type Output = Self;
fn add(self, other: Self) -> Self {
Wealth {
cp: self.cp + other.cp,
sp: self.sp + other.sp,
gp: self.gp + other.gp,
pp: self.pp + other.pp
}
}
}
/// Representation of a new player record /// Representation of a new player record
#[derive(Insertable)] #[derive(Insertable)]
#[table_name = "players"] #[table_name = "players"]

166
src/api.rs Normal file
View File

@@ -0,0 +1,166 @@
use lootalot_db::{self as db, DbConnection, QueryResult};
/// Every possible update which can happen during a query
#[derive(Serialize, Deserialize, Debug)]
pub enum Update {
Wealth(db::Wealth),
ItemAdded(db::Item),
ItemRemoved(db::Item),
ClaimAdded(db::Claim),
ClaimRemoved(db::Claim),
}
/// Every value which can be queried
#[derive(Serialize, Deserialize, Debug)]
pub enum Value {
Item(db::Item),
Claim(db::Claim),
ItemList(Vec<db::Item>),
ClaimList(Vec<db::Claim>),
PlayerList(Vec<db::Player>),
}
/// A generic response for all queries
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct ApiResponse {
/// The value requested, if any
pub value: Option<Value>,
/// A text to notify user, if relevant
pub notification: Option<String>,
/// A list of updates, if any
pub updates: Option<Vec<Update>>,
/// A text describing errors, if any
pub errors: Option<String>,
}
impl ApiResponse {
fn push_update(&mut self, update: Update) {
if let Some(v) = self.updates.as_mut() {
v.push(update);
} else {
self.updates = Some(vec![update]);
}
}
fn push_error<S: Into<String>>(&mut self, error: S) {
if let Some(errors) = self.errors.as_mut() {
*errors = format!("{}\n{}", errors, error.into());
} else {
self.errors = Some(error.into())
}
}
fn set_value(&mut self, value: Value) {
self.value = Some(value);
}
fn notify<S: Into<String>>(&mut self, text: S) {
self.notification = Some(text.into());
}
}
pub enum ApiError {
DieselError(diesel::result::Error),
InvalidAction(String),
}
/// Every allowed queries on the database
pub enum ApiActions {
FetchPlayers,
FetchInventory,
FetchClaims,
// Player actions
FetchLoot(i32),
UpdateWealth(i32, f32),
BuyItems(i32, Vec<(i32, Option<f32>)>),
SellItems(i32, Vec<(i32, Option<f32>)>),
ClaimItem(i32, i32),
UnclaimItem(i32, i32),
// Group actions
AddLoot(Vec<db::Item>),
}
pub enum AdminActions {
AddPlayer(String, f32),
//AddInventoryItem(pub String, pub i32),
ResolveClaims,
//SetClaimsTimeout(pub i32),
}
pub fn execute(
conn: &DbConnection,
query: ApiActions,
) -> Result<ApiResponse, diesel::result::Error> {
let mut response = ApiResponse::default();
match query {
ApiActions::FetchPlayers => {
response.set_value(Value::PlayerList(db::Players(conn).all()?));
}
ApiActions::FetchInventory => {
response.set_value(Value::ItemList(db::Inventory(conn).all()?));
}
ApiActions::FetchClaims => {
response.set_value(Value::ClaimList(db::fetch_claims(conn)?));
}
ApiActions::FetchLoot(id) => {
response.set_value(Value::ItemList(db::LootManager(conn, id).all()?));
}
ApiActions::UpdateWealth(id, amount) => {
response.push_update(Update::Wealth(
db::AsPlayer(conn, id).update_wealth(amount)?,
));
}
ApiActions::BuyItems(id, params) => {
let mut cumulated_diff: Vec<db::Wealth> = Vec::with_capacity(params.len());
let mut added_items: u16 = 0;
for (item_id, price_mod) in params.into_iter() {
// Use a transaction to avoid incoherant state in case of error
if let Ok((item, diff)) = db::buy_item_from_inventory(conn, id, item_id, price_mod) {
cumulated_diff.push(diff);
response.push_update(Update::ItemAdded(item));
added_items += 1;
} else {
response.push_error(format!("Error adding {}", item_id));
}
}
response.notify(format!("Added {} items", added_items));
response.push_update(Update::Wealth(
cumulated_diff
.into_iter()
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i),
));
}
ApiActions::SellItems(id, params) => {
let mut all_results: Vec<db::Wealth> = Vec::with_capacity(params.len());
let mut sold_items: u16 = 0;
for (loot_id, price_mod) in params.into_iter() {
if let Ok((deleted, diff)) = db::sell_item_transaction(conn, id, loot_id, price_mod) {
all_results.push(diff);
response.push_update(Update::ItemRemoved(deleted));
sold_items += 1;
} else {
response.push_error(format!("Error selling {}", loot_id));
}
}
response.notify(format!("Sold {} items", sold_items));
response.push_update(Update::Wealth(
all_results
.into_iter()
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i),
));
}
ApiActions::ClaimItem(id, item) => {
response.push_update(Update::ClaimAdded(
db::Claims(conn).add(id, item)?,
));
}
ApiActions::UnclaimItem(id, item) => {
response.push_update(Update::ClaimRemoved(
db::Claims(conn).remove(id, item)?,
));
}
// Group actions
ApiActions::AddLoot(items) => {}
}
Ok(response)
}

0
src/lib.rs Normal file
View File

View File

@@ -2,9 +2,10 @@ extern crate actix_web;
extern crate dotenv; extern crate dotenv;
extern crate env_logger; extern crate env_logger;
extern crate lootalot_db; extern crate lootalot_db;
extern crate serde; #[macro_use] extern crate serde;
mod server; mod server;
mod api;
fn main() { fn main() {
std::env::set_var("RUST_LOG", "actix_web=info"); std::env::set_var("RUST_LOG", "actix_web=info");

View File

@@ -5,6 +5,7 @@ use futures::Future;
use std::env; use std::env;
use lootalot_db as db; use lootalot_db as db;
use crate::api;
type AppPool = web::Data<db::Pool>; type AppPool = web::Data<db::Pool>;
type PlayerId = web::Path<i32>; type PlayerId = web::Path<i32>;
@@ -14,11 +15,11 @@ type ItemListWithMods = web::Json<Vec<(i32, Option<f32>)>>;
/// Wraps call to the database query and convert its result as a async HttpResponse /// Wraps call to the database query and convert its result as a async HttpResponse
pub fn db_call( pub fn db_call(
pool: AppPool, pool: AppPool,
query: db::ApiActions, query: api::ApiActions,
) -> impl Future<Item = HttpResponse, Error = Error> ) -> impl Future<Item = HttpResponse, Error = Error>
{ {
let conn = pool.get().unwrap(); let conn = pool.get().unwrap();
web::block(move || db::execute(&conn, query)).then(|res| match res { web::block(move || api::execute(&conn, query)).then(|res| match res {
Ok(r) => HttpResponse::Ok().json(r), Ok(r) => HttpResponse::Ok().json(r),
Err(e) => { Err(e) => {
dbg!(&e); dbg!(&e);
@@ -28,13 +29,14 @@ pub fn db_call(
} }
fn configure_app(config: &mut web::ServiceConfig) { fn configure_app(config: &mut web::ServiceConfig) {
use api::ApiActions as Q;
config.service( config.service(
web::scope("/api") web::scope("/api")
.service( .service(
web::scope("/players") web::scope("/players")
.service( .service(
web::resource("/").route( web::resource("/").route(
web::get().to_async(|pool| db_call(pool, db::ApiActions::FetchPlayers)), web::get().to_async(|pool| db_call(pool, Q::FetchPlayers)),
), //.route(web::post().to_async(endpoints::new_player)) ), //.route(web::post().to_async(endpoints::new_player))
) // List of players ) // List of players
.service( .service(
@@ -45,14 +47,14 @@ fn configure_app(config: &mut web::ServiceConfig) {
//.route(web::get().to_async(endpoints::player_claims)) //.route(web::get().to_async(endpoints::player_claims))
.route(web::put().to_async( .route(web::put().to_async(
|pool, (player, data): (PlayerId, ItemId)| { |pool, (player, data): (PlayerId, ItemId)| {
db_call(pool, db::ApiActions::ClaimItem(*player, *data)) db_call(pool, Q::ClaimItem(*player, *data))
}, },
)) ))
.route(web::delete().to_async( .route(web::delete().to_async(
|pool, (player, data): (PlayerId, ItemId)| { |pool, (player, data): (PlayerId, ItemId)| {
db_call( db_call(
pool, pool,
db::ApiActions::UnclaimItem(*player, *data), Q::UnclaimItem(*player, *data),
) )
}, },
)), )),
@@ -64,7 +66,7 @@ fn configure_app(config: &mut web::ServiceConfig) {
|pool, (player, data): (PlayerId, web::Json<f32>)| { |pool, (player, data): (PlayerId, web::Json<f32>)| {
db_call( db_call(
pool, pool,
db::ApiActions::UpdateWealth(*player, *data), Q::UpdateWealth(*player, *data),
) )
}, },
)), )),
@@ -72,26 +74,26 @@ fn configure_app(config: &mut web::ServiceConfig) {
.service( .service(
web::resource("/loot") web::resource("/loot")
.route(web::get().to_async(|pool, player: PlayerId| { .route(web::get().to_async(|pool, player: PlayerId| {
db_call(pool, db::ApiActions::FetchLoot(*player)) db_call(pool, Q::FetchLoot(*player))
})) }))
.route(web::put().to_async( .route(web::put().to_async(
move |pool, (player, data): (PlayerId, ItemListWithMods)| { move |pool, (player, data): (PlayerId, ItemListWithMods)| {
db_call(pool, db::ApiActions::BuyItems(*player, data.into_inner())) db_call(pool, Q::BuyItems(*player, data.into_inner()))
}, },
)) ))
.route(web::delete().to_async( .route(web::delete().to_async(
move |pool, (player, data): (PlayerId, ItemListWithMods)| { move |pool, (player, data): (PlayerId, ItemListWithMods)| {
db_call(pool, db::ApiActions::SellItems(*player, data.into_inner())) db_call(pool, Q::SellItems(*player, data.into_inner()))
}, },
)), )),
), ),
), ),
) )
//.route("/claims", web::get().to_async(endpoints::player_claims)) .route("/claims", web::get().to_async(|pool| db_call(pool, Q::FetchClaims)))
.route( .route(
"/items", "/items",
web::get() web::get()
.to_async(move |pool: AppPool| db_call(pool, db::ApiActions::FetchInventory)), .to_async(move |pool: AppPool| db_call(pool, Q::FetchInventory)),
), ),
); );
} }