moves db logic inside model's managers
This commit is contained in:
@@ -1,4 +1,7 @@
|
||||
use crate::models::item::Loot;
|
||||
use diesel::prelude::*;
|
||||
use crate::{DbConnection, QueryResult};
|
||||
|
||||
use crate::models::{self, item::Loot};
|
||||
use crate::schema::claims;
|
||||
|
||||
/// A Claim is a request by a single player on an item from group chest.
|
||||
@@ -15,6 +18,44 @@ pub struct Claim {
|
||||
pub resolve: i32,
|
||||
}
|
||||
|
||||
pub struct Claims<'q>(pub &'q DbConnection);
|
||||
|
||||
impl<'q> Claims<'q> {
|
||||
|
||||
/// Finds a single claim by id.
|
||||
pub fn find(&self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
|
||||
Ok(
|
||||
claims::table
|
||||
.filter(claims::dsl::player_id.eq(player_id))
|
||||
.filter(claims::dsl::loot_id.eq(loot_id))
|
||||
.first(self.0)?
|
||||
)
|
||||
}
|
||||
|
||||
/// Adds a claim in database and returns it
|
||||
pub fn add(self, player_id: i32, loot_id: i32) -> QueryResult<Claim> {
|
||||
// We need to validate that the claimed item exists, and is actually owned by group (id 0)
|
||||
let exists: bool = diesel::select(Loot::exists(loot_id)).get_result(self.0)?;
|
||||
if !exists {
|
||||
return Err(diesel::result::Error::NotFound);
|
||||
};
|
||||
let claim = NewClaim::new(player_id, loot_id);
|
||||
diesel::insert_into(claims::table)
|
||||
.values(&claim)
|
||||
.execute(self.0)?;
|
||||
// Return the created claim
|
||||
Ok(claims::table.order(claims::dsl::id.desc()).first::<Claim>(self.0)?)
|
||||
}
|
||||
|
||||
/// Removes a claim from database, returning it
|
||||
pub fn remove(self, req_player_id: i32, req_loot_id: i32) -> QueryResult<Claim> {
|
||||
let claim = self.find(req_player_id, req_loot_id)?;
|
||||
diesel::delete(claims::table.find(claim.id))
|
||||
.execute(self.0)?;
|
||||
Ok(claim)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Insertable, Debug)]
|
||||
#[table_name = "claims"]
|
||||
pub(crate) struct NewClaim {
|
||||
|
||||
Reference in New Issue
Block a user