fixes errors, cleans up
This commit is contained in:
@@ -33,8 +33,7 @@ pub type QueryResult<T> = Result<T, diesel::result::Error>;
|
||||
pub type ActionResult<R> = Result<R, diesel::result::Error>;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
enum Update {
|
||||
NoUpdate,
|
||||
pub enum Update {
|
||||
Wealth(Wealth),
|
||||
ItemAdded(Item),
|
||||
ItemRemoved(Item),
|
||||
@@ -43,7 +42,7 @@ enum Update {
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
enum Value {
|
||||
pub enum Value {
|
||||
Item(Item),
|
||||
Claim(Claim),
|
||||
ItemList(Vec<Item>),
|
||||
@@ -53,10 +52,10 @@ enum Value {
|
||||
|
||||
#[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 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
|
||||
pub errors: Option<String>, // A text describing errors, if any
|
||||
}
|
||||
|
||||
impl ApiResponse {
|
||||
@@ -68,6 +67,14 @@ impl ApiResponse {
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -77,24 +84,23 @@ impl ApiResponse {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub enum ApiError {
|
||||
DieselError(diesel::result::Error),
|
||||
InvalidAction(String),
|
||||
}
|
||||
|
||||
pub enum ApiActions<'a> {
|
||||
pub enum ApiActions {
|
||||
FetchPlayers,
|
||||
FetchInventory,
|
||||
// Player actions
|
||||
FetchLoot(i32),
|
||||
UpdateWealth(i32, f32),
|
||||
BuyItems(i32, &'a Vec<(i32, Option<f32>)>),
|
||||
SellItems(i32, &'a Vec<(i32, Option<f32>)>),
|
||||
BuyItems(i32, Vec<(i32, Option<f32>)>),
|
||||
SellItems(i32, Vec<(i32, Option<f32>)>),
|
||||
ClaimItem(i32, i32),
|
||||
UnclaimItem(i32, i32),
|
||||
// Group actions
|
||||
AddLoot(&'a Vec<Item>),
|
||||
AddLoot(Vec<Item>),
|
||||
}
|
||||
|
||||
pub enum AdminActions {
|
||||
@@ -104,38 +110,26 @@ pub enum AdminActions {
|
||||
//SetClaimsTimeout(pub i32),
|
||||
}
|
||||
|
||||
|
||||
pub fn execute<'a>(pool: Pool, query: ApiActions<'a>) -> Result<ApiResponse, diesel::result::Error> {
|
||||
let conn = pool.get().map_err(|e| {dbg!(e); diesel::result::Error::NotFound })?;
|
||||
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(
|
||||
schema::players::table.load::<models::Player>(conn)?
|
||||
)
|
||||
);
|
||||
},
|
||||
response.set_value(Value::PlayerList(models::player::Players(conn).all()?));
|
||||
}
|
||||
ApiActions::FetchInventory => {
|
||||
response.set_value(
|
||||
Value::ItemList(
|
||||
models::item::Inventory(conn).all()?));
|
||||
response.set_value(Value::ItemList(models::item::Inventory(conn).all()?));
|
||||
}
|
||||
ApiActions::FetchLoot(id) => {
|
||||
response.set_value(
|
||||
Value::ItemList(
|
||||
models::item::LootManager(conn, id).all()?
|
||||
)
|
||||
);
|
||||
},
|
||||
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)?
|
||||
)
|
||||
);
|
||||
},
|
||||
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());
|
||||
@@ -143,7 +137,7 @@ pub fn execute<'a>(pool: Pool, query: ApiActions<'a>) -> Result<ApiResponse, die
|
||||
// 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 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,
|
||||
@@ -156,134 +150,92 @@ pub fn execute<'a>(pool: Pool, query: ApiActions<'a>) -> Result<ApiResponse, die
|
||||
cumulated_diff.push(diff);
|
||||
response.push_update(Update::ItemAdded(item));
|
||||
} else {
|
||||
response.errors = Some(format!("Error adding {}", item_id));
|
||||
response.push_error(format!("Error adding {}", item_id));
|
||||
}
|
||||
}
|
||||
let all_diff = cumulated_diff.into_iter().fold(Wealth::from_gp(0.0), |sum, diff|
|
||||
Wealth {
|
||||
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) => {
|
||||
sell(conn, id, params, &mut response);
|
||||
},
|
||||
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)?
|
||||
)
|
||||
);
|
||||
},
|
||||
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)?
|
||||
)
|
||||
);
|
||||
},
|
||||
response.push_update(Update::ClaimRemoved(
|
||||
models::claim::Claims(conn).remove(id, item)?,
|
||||
));
|
||||
}
|
||||
// Group actions
|
||||
ApiActions::AddLoot(items) => {},
|
||||
ApiActions::AddLoot(items) => {}
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// Fetch all existing claims
|
||||
pub fn fetch_claims(conn: &DbConnection) -> QueryResult<Vec<models::Claim>> {
|
||||
schema::claims::table.load::<models::Claim>(conn)
|
||||
}
|
||||
/// Fetch all existing claims
|
||||
pub fn fetch_claims(conn: &DbConnection) -> QueryResult<Vec<models::Claim>> {
|
||||
schema::claims::table.load::<models::Claim>(conn)
|
||||
}
|
||||
|
||||
/// Sell a set of items from this player chest
|
||||
///
|
||||
/// # Returns
|
||||
/// Result containing the difference in coins after operation
|
||||
pub fn sell(
|
||||
conn: &DbConnection,
|
||||
id: i32,
|
||||
params: &Vec<(i32, Option<f32>)>,
|
||||
response: &mut ApiResponse,
|
||||
) {
|
||||
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.errors = Some(format!("Error selling {}", loot_id));
|
||||
/// Resolve all pending claims and dispatch claimed items.
|
||||
///
|
||||
/// When a player gets an item, it's debt is increased by this item sell value
|
||||
pub fn resolve_claims(conn: &DbConnection) -> QueryResult<()> {
|
||||
let data = models::claim::Claims(conn).grouped_by_item()?;
|
||||
dbg!(&data);
|
||||
|
||||
for (item, claims) in data {
|
||||
match claims.len() {
|
||||
1 => {
|
||||
let claim = claims.get(0).unwrap();
|
||||
let player_id = claim.player_id;
|
||||
conn.transaction(|| {
|
||||
claim.resolve_claim(conn)?;
|
||||
//models::item::LootManager(self.0, 0).set_owner(claim.loot_id, claim.player_id)?;
|
||||
models::player::AsPlayer(conn, player_id).update_debt(item.sell_value())
|
||||
})?;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
/// Wrapper for interactions of admins with the DB.
|
||||
pub struct AsAdmin<'q>(&'q DbConnection);
|
||||
|
||||
impl<'q> AsAdmin<'q> {
|
||||
/// Adds a player to the database
|
||||
///
|
||||
/// Takes the player name and starting wealth (in gold value).
|
||||
pub fn add_player(self, name: &str, start_wealth: f32) -> ActionResult<()> {
|
||||
models::player::Players(self.0).add(name, start_wealth)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds a list of items to the group loot
|
||||
pub fn add_loot(self, items: Vec<models::item::Item>) -> ActionResult<()> {
|
||||
for item_desc in items.iter() {
|
||||
models::item::LootManager(self.0, 0).add_from(item_desc)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve all pending claims and dispatch claimed items.
|
||||
///
|
||||
/// When a player gets an item, it's debt is increased by this item sell value
|
||||
pub fn resolve_claims(self) -> ActionResult<()> {
|
||||
let data = models::claim::Claims(self.0).grouped_by_item()?;
|
||||
dbg!(&data);
|
||||
|
||||
for (item, claims) in data {
|
||||
match claims.len() {
|
||||
1 => {
|
||||
let claim = claims.get(0).unwrap();
|
||||
let player_id = claim.player_id;
|
||||
self.0.transaction(|| {
|
||||
claim.resolve_claim(self.0)?;
|
||||
//models::item::LootManager(self.0, 0).set_owner(claim.loot_id, claim.player_id)?;
|
||||
models::player::AsPlayer(self.0, player_id).update_debt(item.sell_value())
|
||||
})?;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets up a connection pool and returns it.
|
||||
|
||||
Reference in New Issue
Block a user