moves API logic inside its own module
This commit is contained in:
@@ -19,8 +19,8 @@ mod schema;
|
||||
|
||||
pub use models::{
|
||||
claim::{Claim, Claims},
|
||||
item::{Item, LootManager},
|
||||
player::{Player, Players, Wealth},
|
||||
item::{Item, LootManager, Inventory},
|
||||
player::{Player, Wealth, Players, AsPlayer},
|
||||
};
|
||||
|
||||
/// The connection used
|
||||
@@ -29,184 +29,66 @@ pub type DbConnection = SqliteConnection;
|
||||
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
|
||||
/// The result of a query on DB
|
||||
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)]
|
||||
pub enum Update {
|
||||
Wealth(Wealth),
|
||||
ItemAdded(Item),
|
||||
ItemRemoved(Item),
|
||||
ClaimAdded(Claim),
|
||||
ClaimRemoved(Claim),
|
||||
/// 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.")
|
||||
}
|
||||
|
||||
#[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)]
|
||||
pub struct ApiResponse {
|
||||
pub value: Option<Value>, // The value requested, if any
|
||||
pub notify: Option<String>, // A text to notify user, if relevant
|
||||
pub updates: Option<Vec<Update>>, // A list of updates, if any
|
||||
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(
|
||||
/// Sells a single item inside a transaction
|
||||
///
|
||||
/// # Returns
|
||||
/// The deleted entity and the updated Wealth (as a difference from previous value)
|
||||
pub fn sell_item_transaction(
|
||||
conn: &DbConnection,
|
||||
query: ApiActions,
|
||||
) -> Result<ApiResponse, diesel::result::Error> {
|
||||
let mut response = ApiResponse::default();
|
||||
match query {
|
||||
ApiActions::FetchPlayers => {
|
||||
response.set_value(Value::PlayerList(models::player::Players(conn).all()?));
|
||||
id: i32,
|
||||
loot_id: i32,
|
||||
price_mod: Option<f32>,
|
||||
) -> QueryResult<(Item, Wealth)> {
|
||||
conn.transaction(|| {
|
||||
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 => {
|
||||
response.set_value(Value::ItemList(models::item::Inventory(conn).all()?));
|
||||
}
|
||||
ApiActions::FetchLoot(id) => {
|
||||
response.set_value(Value::ItemList(models::item::LootManager(conn, id).all()?));
|
||||
}
|
||||
ApiActions::UpdateWealth(id, amount) => {
|
||||
response.push_update(Update::Wealth(
|
||||
models::player::AsPlayer(conn, id).update_wealth(amount)?,
|
||||
));
|
||||
}
|
||||
ApiActions::BuyItems(id, params) => {
|
||||
let mut cumulated_diff: Vec<Wealth> = Vec::with_capacity(params.len());
|
||||
let mut added_items: Vec<models::Item> = Vec::with_capacity(params.len());
|
||||
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)) = conn.transaction(|| {
|
||||
// Find item in inventory
|
||||
let item = models::item::Inventory(conn).find(item_id)?;
|
||||
let new_item = models::item::LootManager(conn, id).add_from(&item)?;
|
||||
let sell_price = match price_mod {
|
||||
Some(modifier) => item.base_price as f32 * modifier,
|
||||
None => item.base_price as f32,
|
||||
};
|
||||
models::player::AsPlayer(conn, id)
|
||||
.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)
|
||||
let wealth = AsPlayer(conn, id)
|
||||
.update_wealth(sell_value)?;
|
||||
Ok((deleted, wealth))
|
||||
})
|
||||
}
|
||||
|
||||
/// Buys a single item, copied from inventory.
|
||||
/// Runs inside a transaction
|
||||
///
|
||||
/// # Returns
|
||||
/// The created entity and the updated Wealth (as a difference from previous value)
|
||||
pub fn buy_item_from_inventory(
|
||||
conn: &DbConnection,
|
||||
id: i32,
|
||||
item_id: i32,
|
||||
price_mod: Option<f32>,
|
||||
) -> QueryResult<(Item, Wealth)> {
|
||||
conn.transaction(|| {
|
||||
// Find item in inventory
|
||||
let item = Inventory(conn).find(item_id)?;
|
||||
let new_item = LootManager(conn, id).add_from(&item)?;
|
||||
let sell_price = match price_mod {
|
||||
Some(modifier) => item.base_price as f32 * modifier,
|
||||
None => item.base_price as f32,
|
||||
};
|
||||
AsPlayer(conn, id)
|
||||
.update_wealth(-sell_price)
|
||||
.map(|diff| (new_item, diff))
|
||||
})
|
||||
}
|
||||
|
||||
/// Fetch all existing claims
|
||||
@@ -238,16 +120,6 @@ pub fn resolve_claims(conn: &DbConnection) -> QueryResult<()> {
|
||||
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)]
|
||||
mod tests_old {
|
||||
|
||||
Reference in New Issue
Block a user