8 Commits

Author SHA1 Message Date
08f29fc90e this looks this overdoing it... going back to master 2019-07-24 13:45:03 +02:00
4f60df88d7 moves player actions code inside UserAction trait impls 2019-07-20 15:49:51 +02:00
51a3d00d03 formats code 2019-07-20 15:00:28 +02:00
0636829fdd adds doc 2019-07-17 14:59:04 +02:00
143d9bb5aa adds tests 2019-07-17 14:26:27 +02:00
21369535e8 impls more DbApi actions, adds a test 2019-07-16 14:56:54 +02:00
441b7f5ad6 little fixes 2019-07-15 16:07:25 +02:00
4b55964786 adds comments and new tests 2019-07-15 15:55:13 +02:00
7 changed files with 589 additions and 94 deletions

View File

@@ -13,8 +13,10 @@ use diesel::prelude::*;
use diesel::query_dsl::RunQueryDsl;
use diesel::r2d2::{self, ConnectionManager};
mod transactions;
pub mod models;
mod schema;
use transactions::{DbTransaction};
/// The connection used
pub type DbConnection = SqliteConnection;
@@ -22,11 +24,8 @@ 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> = QueryResult<ActionStatus<R>>;
/// Return status of an API Action
///
pub type ActionResult<T> = QueryResult<ActionStatus<T>>;
/// Return status of an Action
#[derive(Serialize, Debug)]
pub struct ActionStatus<R: serde::Serialize> {
/// Has the action made changes ?
@@ -36,47 +35,46 @@ pub struct ActionStatus<R: serde::Serialize> {
}
impl ActionStatus<()> {
fn was_updated(updated_lines: usize) -> Self {
pub fn was_updated(updated_lines: usize) -> Self {
match updated_lines {
1 => Self::ok(),
_ => Self::nop(),
}
}
fn ok() -> ActionStatus<()> {
pub fn ok() -> ActionStatus<()> {
Self {
executed: true,
response: (),
}
}
fn nop() -> ActionStatus<()> {
}
impl<T: Default + serde::Serialize> ActionStatus<T> {
pub fn nop() -> ActionStatus<T> {
Self {
executed: false,
response: (),
response: Default::default(),
}
}
}
/// A wrapper providing an API over the database
/// It offers a convenient way to deal with connection
/// It offers a convenient way to deal with connection.
///
/// # Note
/// All methods consumes the DbApi, so that only one action
/// can be performed using a single instance.
///
/// # Todo list
/// ```text
/// struct DbApi<'q>(&'q DbConnection);
/// ::new() -> DbApi<'q> (Db finds a connection by itself, usefull for cli)
/// ::with_conn(conn) -> DbApi<'q> (uses a user-defined connection)
/// v .fetch_players()
/// v .fetch_inventory()
/// v .fetch_claims()
/// v .as_player(player_id) -> AsPlayer<'q>
/// v .loot() -> List of items owned (Vec<Item>)
/// v .claim(loot_id) -> Success status (bool)
/// v .unclaim(loot_id) -> Success status (bool)
/// x .sell(loot_id) -> Success status (bool, earned)
/// x .buy(item_desc) -> Success status (bool, cost)
/// v .update_wealth(value_in_gold) -> Success status (bool, new_wealth)
/// v .as_player()
/// // Needs an action's history (one entry only should be enough)
/// x .undo_last_action() -> Success status
/// v .as_admin()
/// x .add_loot(identifier, [items_desc]) -> Success status
/// // When adding loot, an identifier should be used to build some kind of history
/// vx .add_loot(identifier, [items_desc]) -> Success status
/// x .sell_loot([players], [excluded_item_ids]) -> Success status (bool, player_share)
/// // Claims should be resolved after a certain delay
/// x .set_claims_timeout()
/// x .resolve_claims()
/// v .add_player(player_data)
/// ```
@@ -154,58 +152,98 @@ impl<'q> AsPlayer<'q> {
pub fn loot(self) -> QueryResult<Vec<models::Item>> {
Ok(models::Item::owned_by(self.id).load(self.conn)?)
}
/// Buy an item and add it to this player chest
///
/// TODO: Items should be picked from a custom list
///
/// # Panics
///
/// This currently panics if player wealth fails to be updated, as this is
/// a serious error. TODO: handle deletion of bought item in case of wealth update failure.
pub fn buy<S: Into<String>>(self, name: S, price: i32) -> ActionResult<Option<(i32, i32, i32, i32)>> {
match transactions::player::Buy.execute(
self.conn,
transactions::player::AddLootParams {
player_id: self.id,
loot_name: name.into(),
loot_price: price,
},
) {
Ok(res) => Ok(ActionStatus { executed: true, response: Some(res.loot_cost) }),
Err(e) => { dbg!(&e); Ok(ActionStatus { executed: false, response: None}) },
}
}
/// Sell an item from this player chest
///
/// # Panics
///
/// This currently panics if player wealth fails to be updated, as this is
/// a serious error. TODO: handle restoring of sold item in case of wealth update failure.
pub fn sell(
self,
loot_id: i32,
_price_mod: Option<f32>,
) -> ActionResult<Option<(i32, i32, i32, i32)>> {
// Check that the item belongs to player
let exists_and_owned: bool =
diesel::select(models::Loot::owns(self.id, loot_id))
.get_result(self.conn)?;
if !exists_and_owned {
return Ok(ActionStatus::nop());
}
transactions::player::Sell.execute(
self.conn,
transactions::player::LootParams {
player_id: self.id,
loot_id,
},
)
.map(|res| ActionStatus { executed: true, response: Some(res.loot_cost) })
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop()) })
}
/// Adds the value in gold to the player's wealth.
///
/// Value can be negative to substract wealth.
pub fn update_wealth(self, value_in_gp: f32) -> ActionResult<Option<(i32, i32, i32, i32)>> {
use schema::players::dsl::*;
let current_wealth = players
.find(self.id)
.select((cp, sp, gp, pp))
.first::<models::Wealth>(self.conn)?;
// TODO: improve this
// should be move inside a WealthUpdate method
let update = models::Wealth::from_gp(current_wealth.to_gp() + value_in_gp);
// Difference in coins that is sent back
let (old, new) = (current_wealth.as_tuple(), update.as_tuple());
let diff = (new.0 - old.0, new.1 - old.1, new.2 - old.2, new.3 - old.3);
diesel::update(players)
.filter(id.eq(self.id))
.set(&update)
.execute(self.conn)
.map(|r| match r {
1 => ActionStatus {
executed: true,
response: Some(diff),
},
_ => ActionStatus {
executed: false,
response: None,
},
})
transactions::player::UpdateWealth.execute(
self.conn,
transactions::player::WealthParams {
player_id: self.id,
value_in_gp,
},
)
.map(|res| ActionStatus { executed: true, response: Some(res) })
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
}
/// Put a claim on a specific item
pub fn claim(self, item: i32) -> ActionResult<()> {
// TODO: check that looted item exists
let exists: bool = diesel::select(models::Loot::exists(item)).get_result(self.conn)?;
let exists: bool =
diesel::select(models::Loot::exists(item)).get_result(self.conn)?;
if !exists {
return Ok(ActionStatus::nop());
};
let claim = models::claim::NewClaim::new(self.id, item);
diesel::insert_into(schema::claims::table)
.values(&claim)
.execute(self.conn)
.map(ActionStatus::was_updated)
transactions::player::PutClaim.execute(
self.conn,
transactions::player::LootParams {
player_id: self.id,
loot_id: item,
},
)
.map(|_| ActionStatus { executed: true, response: () })
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
}
/// Withdraw claim
pub fn unclaim(self, item: i32) -> ActionResult<()> {
use schema::claims::dsl::*;
diesel::delete(
claims.filter(loot_id.eq(item))
.filter(player_id.eq(self.id)),
)
.execute(self.conn)
.map(ActionStatus::was_updated)
transactions::player::WithdrawClaim.execute(
self.conn,
transactions::player::LootParams {
player_id: self.id,
loot_id: item,
},
)
.map(|_| ActionStatus { executed: true, response: () })
.or_else(|e| { dbg!(&e); Ok(ActionStatus::nop())})
}
}
@@ -213,6 +251,9 @@ impl<'q> AsPlayer<'q> {
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: String, start_wealth: f32) -> ActionResult<()> {
diesel::insert_into(schema::players::table)
.values(&models::player::NewPlayer::create(&name, start_wealth))
@@ -220,6 +261,20 @@ impl<'q> AsAdmin<'q> {
.map(ActionStatus::was_updated)
}
/// Adds a list of items to the group loot
pub fn add_loot<'a>(self, items: Vec<(&'a str, i32)>) -> ActionResult<()> {
for item_desc in items.into_iter() {
let new_item = models::item::NewLoot::to_group(item_desc);
diesel::insert_into(schema::looted::table)
.values(&new_item)
.execute(self.0)?;
}
Ok(ActionStatus::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<()> {
// Fetch all claims, grouped by items.
let loot = models::Loot::owned_by(0).load(self.0)?;
@@ -235,7 +290,7 @@ impl<'q> AsAdmin<'q> {
}
}
/// Create a connection pool and returns it.
/// 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");
@@ -251,12 +306,15 @@ mod tests {
use super::*;
type TestConnection = DbConnection;
/// Return a connection to a fresh database (stored in memory)
fn test_connection() -> TestConnection {
let test_conn = DbConnection::establish(":memory:").unwrap();
diesel_migrations::run_pending_migrations(&test_conn).unwrap();
test_conn
}
/// When migrations are run, a special player with id 0 and name "Groupe"
/// must be created.
#[test]
fn test_group_is_autocreated() {
let conn = test_connection();
@@ -267,15 +325,21 @@ mod tests {
assert_eq!(group.name, "Groupe".to_string());
}
/// When a player updates wealth, a difference is returned by API.
/// Added to the previous amount of coins, it should equal the updated weath.
#[test]
fn test_player_updates_wealth() {
let conn = test_connection();
DbApi::with_conn(&conn).as_admin()
DbApi::with_conn(&conn)
.as_admin()
.add_player("PlayerName".to_string(), 403.21)
.unwrap();
let diff = DbApi::with_conn(&conn).as_player(1)
.update_wealth(-401.21).unwrap()
.response.unwrap();
let diff = DbApi::with_conn(&conn)
.as_player(1)
.update_wealth(-401.21)
.unwrap()
.response
.unwrap();
// Check the returned diff
assert_eq!(diff, (-1, -2, -1, -4));
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
@@ -288,9 +352,10 @@ mod tests {
}
#[test]
fn test_add_player() {
fn test_admin_add_player() {
let conn = test_connection();
let result = DbApi::with_conn(&conn).as_admin()
let result = DbApi::with_conn(&conn)
.as_admin()
.add_player("PlayerName".to_string(), 403.21)
.unwrap();
assert_eq!(result.executed, true);
@@ -298,8 +363,127 @@ mod tests {
assert_eq!(players.len(), 2);
let new_player = players.get(1).unwrap();
assert_eq!(new_player.name, "PlayerName");
assert_eq!((new_player.cp, new_player.sp, new_player.gp, new_player.pp), (1, 2, 3, 4));
assert_eq!(
(new_player.cp, new_player.sp, new_player.gp, new_player.pp),
(1, 2, 3, 4)
);
}
#[test]
fn test_admin_resolve_claims() {
let conn = test_connection();
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
assert_eq!(claims.len(), 0);
assert_eq!(true, false); // Failing as test is not complete
}
#[test]
fn test_player_claim_item() {
let conn = test_connection();
DbApi::with_conn(&conn)
.as_admin()
.add_player("Player".to_string(), 0.0)
.unwrap();
DbApi::with_conn(&conn)
.as_admin()
.add_loot(vec![("Épée", 25)])
.unwrap();
// Claim an existing item
let result = DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
assert_eq!(result.executed, true);
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
assert_eq!(claims.len(), 1);
let claim = claims.get(0).unwrap();
assert_eq!(claim.player_id, 1);
assert_eq!(claim.loot_id, 1);
// Claim an inexistant item
let result = DbApi::with_conn(&conn).as_player(1).claim(2).unwrap();
assert_eq!(result.executed, false);
}
#[test]
fn test_player_unclaim_item() {
let conn = test_connection();
DbApi::with_conn(&conn)
.as_admin()
.add_player("Player".to_string(), 0.0)
.unwrap();
DbApi::with_conn(&conn)
.as_admin()
.add_loot(vec![("Épée", 25)])
.unwrap();
// Claim an existing item
let result = DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
assert_eq!(result.executed, true);
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1).unwrap();
assert_eq!(result.executed, true);
// Check that unclaimed items will not be unclaimed...
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1).unwrap();
assert_eq!(result.executed, false);
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
assert_eq!(claims.len(), 0);
}
/// All-in-one checks one a simple buy/sell procedure
///
/// Checks that player's chest and wealth are updated.
/// Checks that items are sold at half their value.
#[test]
fn test_buy_sell_simple() {
let conn = test_connection();
DbApi::with_conn(&conn)
.as_admin()
.add_player("Player".to_string(), 1000.0)
.unwrap();
// Buy an item
let bought = DbApi::with_conn(&conn)
.as_player(1)
.buy("Sword", 800)
.unwrap();
assert_eq!(bought.executed, true); // Was updated ?
assert_eq!(bought.response, Some((0, 0, 0, -8))); // Returns diff of player wealth ?
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
assert_eq!(chest.len(), 1);
let loot = chest.get(0).unwrap();
assert_eq!(loot.name, "Sword");
assert_eq!(loot.base_price, 800);
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
let player = players.get(1).unwrap();
assert_eq!(player.pp, 2);
// Sell back
let sold = DbApi::with_conn(&conn)
.as_player(1)
.sell(loot.id, None)
.unwrap();
assert_eq!(sold.executed, true);
assert_eq!(sold.response, Some((0, 0, 0, 4)));
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
assert_eq!(chest.len(), 0);
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
let player = players.get(1).unwrap();
assert_eq!(player.pp, 6);
}
#[test]
fn test_admin_add_loot() {
let conn = test_connection();
assert_eq!(
0,
DbApi::with_conn(&conn).as_player(0).loot().unwrap().len()
);
let loot_to_add = vec![("Cape d'invisibilité", 8000), ("Arc long", 25)];
let result = DbApi::with_conn(&conn)
.as_admin()
.add_loot(loot_to_add.clone())
.unwrap();
assert_eq!(result.executed, true);
let looted = DbApi::with_conn(&conn).as_player(0).loot().unwrap();
assert_eq!(looted.len(), 2);
// NB: Not a problem now, but this adds constraints of items being
// created in the same order.
for (added, to_add) in looted.into_iter().zip(loot_to_add) {
assert_eq!(added.name, to_add.0);
assert_eq!(added.base_price, to_add.1);
}
}
}

View File

@@ -24,9 +24,6 @@ pub(crate) struct NewClaim {
impl NewClaim {
pub(crate) fn new(player_id: i32, loot_id: i32) -> Self {
Self {
player_id,
loot_id
}
Self { player_id, loot_id }
}
}

View File

@@ -1,4 +1,4 @@
use crate::schema::{looted};
use crate::schema::looted;
use diesel::dsl::{exists, Eq, Filter, Find, Select};
use diesel::expression::exists::Exists;
use diesel::prelude::*;
@@ -14,9 +14,9 @@ type OwnedBy = Select<OwnedLoot, ItemColumns>;
/// Or maybe this is a little too confusing ??
#[derive(Debug, Queryable, Serialize)]
pub struct Item {
id: i32,
name: String,
base_price: i32,
pub id: i32,
pub name: String,
pub base_price: i32,
}
impl Item {
@@ -35,7 +35,7 @@ type OwnedLoot = Filter<looted::table, WithOwner>;
pub(crate) struct Loot {
id: i32,
name: String,
base_value: i32,
base_price: i32,
owner: i32,
}
@@ -45,13 +45,17 @@ impl Loot {
looted::table.filter(looted::owner_id.eq(id))
}
pub(crate) fn owns(player: i32, item: i32) -> Exists<Find<OwnedLoot, i32>> {
exists(Loot::owned_by(player).find(item))
}
pub(crate) fn exists(id: i32) -> Exists<Find<looted::table, i32>> {
exists(looted::table.find(id))
}
}
/// Description of an item : (name, value in gold)
type ItemDesc<'a> = (&'a str, i32);
pub type ItemDesc<'a> = (&'a str, i32);
/// An item being looted or bought.
///

View File

@@ -99,7 +99,10 @@ impl<'a> NewPlayer<'a> {
let (cp, sp, gp, pp) = Wealth::from_gp(wealth_in_gp).as_tuple();
Self {
name,
cp, sp, gp, pp,
cp,
sp,
gp,
pp,
}
}
}

View File

@@ -0,0 +1,295 @@
//! TODO:
//! Extract actions provided by API into their dedicated module.
//! Will allow more flexibilty to combinate them inside API methods.
//! Should make it easier to add a new feature : Reverting an action
//!
use crate::models;
use crate::schema;
use crate::DbConnection;
use diesel::prelude::*;
// TODO: revertable actions :
// - Buy
// - Sell
// - UpdateWealth
pub type TransactionResult<T> = Result<T, diesel::result::Error>;
pub trait DbTransaction {
type Params;
type Response: serde::Serialize;
fn execute<'q>(
self,
conn: &'q DbConnection,
params: Self::Params,
) -> TransactionResult<Self::Response>;
}
pub trait Revertable : DbTransaction {
fn revert<'q>(
self,
conn: &'q DbConnection,
player_id: i32,
params: <Self as DbTransaction>::Response,
) -> TransactionResult<<Self as DbTransaction>::Response>;
}
/// Return status of an Action
#[derive(Serialize, Debug)]
pub struct ActionStatus<R: serde::Serialize> {
/// Has the action made changes ?
pub executed: bool,
/// Response payload
pub response: R,
}
impl ActionStatus<()> {
pub fn was_updated(updated_lines: usize) -> Self {
match updated_lines {
1 => Self::ok(),
_ => Self::nop(),
}
}
pub fn ok() -> ActionStatus<()> {
Self {
executed: true,
response: (),
}
}
}
impl<T: Default + serde::Serialize> ActionStatus<T> {
pub fn nop() -> ActionStatus<T> {
Self {
executed: false,
response: Default::default(),
}
}
}
// Or a module ?
pub(crate) mod player {
use super::*;
pub struct AddLootParams {
pub player_id: i32,
pub loot_name: String,
pub loot_price: i32,
}
pub struct Buy;
enum LootTransactionKind {
Buy,
Sell,
}
#[derive(Serialize, Debug)]
pub struct LootTransaction {
player_id: i32,
loot_id: i32,
kind: LootTransactionKind,
pub loot_cost: (i32, i32, i32, i32),
}
impl DbTransaction for Buy {
type Params = AddLootParams;
type Response = LootTransaction;
fn execute<'q>(
self,
conn: &'q DbConnection,
params: Self::Params,
) -> TransactionResult<Self::Response> {
let added_item = {
let new_item = models::item::NewLoot::to_player(
params.player_id,
(&params.loot_name, params.loot_price),
);
diesel::insert_into(schema::looted::table)
.values(&new_item)
.execute(conn)?
// TODO: return ID of inserted item
};
let updated_wealth = UpdateWealth.execute(
conn,
WealthParams {
player_id: params.player_id,
value_in_gp: -(params.loot_price as f32),
},
);
match (added_item, updated_wealth) {
(1, Ok(loot_cost)) => Ok(LootTransaction {
kind: LootTransactionKind::Buy,
player_id: params.player_id,
loot_id: 0, //TODO: find added item ID
loot_cost,
}),
// TODO: Handle other cases
_ => panic!()
}
}
}
impl Revertable for Buy {
fn revert<'q>(self, conn: &'q DbConnection, player_id: i32, params: <Self as DbTransaction>::Response)
-> TransactionResult<<Self as DbTransaction>::Response> {
unimplemented!()
}
}
pub struct LootParams {
pub player_id: i32,
pub loot_id: i32,
}
pub struct Sell;
impl DbTransaction for Sell {
type Params = LootParams;
type Response = LootTransaction;
fn execute<'q>(
self,
conn: &DbConnection,
params: Self::Params,
) -> TransactionResult<Self::Response> {
use schema::looted::dsl::*;
let loot_value = looted
.find(params.loot_id)
.select(base_price)
.first::<i32>(conn)?;
let sell_value = (loot_value / 2) as f32;
diesel::delete(looted.find(params.loot_id))
.execute(conn)
.and_then(|r| match r {
// On deletion, update this player wealth
1 => Ok(UpdateWealth
.execute(
conn,
WealthParams {
player_id: params.player_id,
value_in_gp: sell_value as f32,
},
)
.unwrap()),
_ => Ok(ActionStatus {
executed: false,
response: None,
}),
})
}
}
pub struct PutClaim;
impl DbTransaction for PutClaim {
type Params = LootParams;
type Response = ();
fn execute<'q>(
self,
conn: &DbConnection,
params: Self::Params,
) -> TransactionResult<Self::Response> {
let claim = models::claim::NewClaim::new(params.player_id, params.loot_id);
diesel::insert_into(schema::claims::table)
.values(&claim)
.execute(conn)
.and_then(|_| Ok(()))
}
}
pub struct WithdrawClaim;
impl DbTransaction for WithdrawClaim {
type Params = LootParams;
type Response = ();
fn execute<'q>(
self,
conn: &DbConnection,
params: Self::Params,
) -> TransactionResult<Self::Response> {
use schema::claims::dsl::*;
diesel::delete(
claims
.filter(loot_id.eq(params.loot_id))
.filter(player_id.eq(params.player_id)),
)
.execute(conn)
.and_then(|_| Ok(()))
}
}
pub struct WealthParams {
pub player_id: i32,
pub value_in_gp: f32,
}
pub struct UpdateWealth;
impl DbTransaction for UpdateWealth {
type Params = WealthParams;
type Response = (i32, i32, i32, i32);
fn execute<'q>(
self,
conn: &'q DbConnection,
params: WealthParams,
) -> TransactionResult<Self::Response> {
use schema::players::dsl::*;
let current_wealth = players
.find(params.player_id)
.select((cp, sp, gp, pp))
.first::<models::Wealth>(conn)?;
// TODO: improve thisdiesel dependant transaction
// should be move inside a WealthUpdate method
let updated_wealth =
models::Wealth::from_gp(current_wealth.to_gp() + params.value_in_gp);
// Difference in coins that is sent back
let (old, new) = (current_wealth.as_tuple(), updated_wealth.as_tuple());
let diff = (new.0 - old.0, new.1 - old.1, new.2 - old.2, new.3 - old.3);
diesel::update(players)
.filter(id.eq(params.player_id))
.set(&updated_wealth)
.execute(conn)
.and_then(|r| match r {
1 => Ok(diff),
_ => panic!("UpdateWealth made no changes !"),
})
}
}
impl Revertable for UpdateWealth {
fn revert<'q>(
self,
conn: &'q DbConnection,
player_id: i32,
params: <Self as DbTransaction>::Response,
) -> TransactionResult<<Self as DbTransaction>::Response> {
use schema::players::dsl::*;
let cur_wealth = players
.find(player_id)
.select((cp, sp, gp, pp))
.first::<models::Wealth>(conn)?;
let reverted_wealth = models::player::Wealth {
cp: cur_wealth.cp - params.0,
sp: cur_wealth.cp - params.1,
gp: cur_wealth.cp - params.2,
pp: cur_wealth.cp - params.3,
};
// Difference in coins that is sent back
let diff = ( -params.0, -params.1, -params.2, -params.3);
diesel::update(players)
.filter(id.eq(params.0))
.set(&reverted_wealth)
.execute(conn)
.and_then(|r| match r {
1 => Ok(diff),
_ => panic!("RevertableWealthUpdate made no changes"),
})
}
}
}
pub(crate) mod admin {
pub struct AddPlayer;
pub struct AddLoot;
pub struct SellLoot;
pub struct ResolveClaims;
}

View File

@@ -13,5 +13,5 @@ fn main() {
// Server is started with 'serve' subcommand
// $ lootalot serve
// Start the server.
server::serve();
server::serve().ok();
}

View File

@@ -65,8 +65,18 @@ pub(crate) fn serve() -> std::io::Result<()> {
)
.service(
web::scope("/api")
.route("/players", web::get().to_async(move |pool: AppPool| db_call(pool, move |api| api.fetch_players())))
.route("/claims", web::get().to_async(move |pool: AppPool| db_call(pool, move |api| api.fetch_claims())))
.route(
"/players",
web::get().to_async(move |pool: AppPool| {
db_call(pool, move |api| api.fetch_players())
}),
)
.route(
"/claims",
web::get().to_async(move |pool: AppPool| {
db_call(pool, move |api| api.fetch_claims())
}),
)
.route(
"/{player_id}/update-wealth/{amount}",
web::get().to_async(move |pool: AppPool, data: web::Path<(i32, f32)>| {
@@ -99,12 +109,14 @@ pub(crate) fn serve() -> std::io::Result<()> {
)
.route(
"/admin/add-player/{name}/{wealth}",
web::get().to_async(move |pool: AppPool, data: web::Path<(String, f32)>| {
db_call(pool, move |api| {
api.as_admin().add_player(data.0.clone(), data.1)
})
}),
)
web::get().to_async(
move |pool: AppPool, data: web::Path<(String, f32)>| {
db_call(pool, move |api| {
api.as_admin().add_player(data.0.clone(), data.1)
})
},
),
),
)
.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
})