moves db logic inside model's managers
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
use diesel::prelude::*;
|
||||
use crate::{DbConnection, QueryResult};
|
||||
use crate::schema::players;
|
||||
|
||||
/// Representation of a player in database
|
||||
@@ -20,6 +22,32 @@ pub struct Player {
|
||||
pub pp: i32,
|
||||
}
|
||||
|
||||
pub struct AsPlayer<'q>(pub &'q DbConnection, pub i32);
|
||||
|
||||
impl<'q> AsPlayer<'q> {
|
||||
pub fn update_wealth(&self, value_in_gp: f32) -> QueryResult<Wealth> {
|
||||
use crate::schema::players::dsl::*;
|
||||
let current_wealth = players
|
||||
.find(self.1)
|
||||
.select((cp, sp, gp, pp))
|
||||
.first::<Wealth>(self.0)?;
|
||||
let updated_wealth = Wealth::from_gp(current_wealth.to_gp() + value_in_gp);
|
||||
// Difference in coins that is sent back
|
||||
let difference = Wealth {
|
||||
cp: updated_wealth.cp - current_wealth.cp,
|
||||
sp: updated_wealth.sp - current_wealth.sp,
|
||||
gp: updated_wealth.gp - current_wealth.gp,
|
||||
pp: updated_wealth.pp - current_wealth.pp,
|
||||
};
|
||||
diesel::update(players)
|
||||
.filter(id.eq(self.1))
|
||||
.set(&updated_wealth)
|
||||
.execute(self.0)?;
|
||||
Ok(difference)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Unpack a floating value of gold pieces to integer
|
||||
/// values of copper, silver, gold and platinum pieces
|
||||
///
|
||||
|
||||
Reference in New Issue
Block a user