Skip to content

Commit

Permalink
fix: self attack game table row creation
Browse files Browse the repository at this point in the history
  • Loading branch information
Shriram-10 committed Feb 16, 2025
1 parent 2c2ae4d commit 65b9e35
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
10 changes: 5 additions & 5 deletions src/api/attack/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ async fn init_attack(
is_self: web::Query<HashMap<String, bool>>,
) -> Result<impl Responder> {
let attacker_id = user.0;

let is_self_attack = *is_self.get("is_self").unwrap_or(&false);
log::info!("Attacker:{} is trying to initiate an attack", attacker_id);
let mut conn = pool.get().map_err(|err| error::handle_error(err.into()))?;
if let Ok(check) = util::can_attack_happen(&mut conn, attacker_id, true) {
Expand All @@ -73,7 +73,7 @@ async fn init_attack(
.map_err(|err| error::handle_error(err.into()))?;

let opponent_id: i32;
if *is_self.get("is_self").unwrap_or(&false) {
if is_self_attack {
opponent_id = attacker_id;
} else {
let random_opponent_id = web::block(move || {
Expand Down Expand Up @@ -142,10 +142,10 @@ async fn init_attack(

log::info!("User details fetched for Opponent:{}", opponent_id);

//Create game
//Create a new game
let mut conn = pool.get().map_err(|err| error::handle_error(err.into()))?;
let game_id = web::block(move || {
Ok(util::add_game(attacker_id, opponent_id, map_id, &mut conn)?) as anyhow::Result<i32>
Ok(util::add_game(attacker_id, opponent_id, map_id, &mut conn, is_self_attack)?) as anyhow::Result<i32>
})
.await?
.map_err(|err| error::handle_error(err.into()))?;
Expand Down Expand Up @@ -244,7 +244,7 @@ async fn socket_handler(
} else {
if attacker_id != defender_id {
log::info!("Attacker:{} is trying to attack someone else", attacker_id);
return Err(ErrorBadRequest("Can't attack yourself"));
return Err(ErrorBadRequest("Can't attack someone else"));
}
}

Expand Down
12 changes: 8 additions & 4 deletions src/api/attack/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ pub fn add_game(
defender_id: i32,
map_layout_id: i32,
conn: &mut PgConnection,
is_self_attack: bool,
) -> Result<i32> {
use crate::schema::game;

Expand All @@ -160,17 +161,20 @@ pub fn add_game(
is_game_over: &false,
date: &chrono::Local::now().date_naive(),
};

let inserted_game: Game = diesel::insert_into(game::table)
let inserted_game: Game;
if !is_self_attack {
inserted_game = diesel::insert_into(game::table)
.values(&new_game)
.get_result(conn)
.map_err(|err| DieselError {
table: "game",
function: function!(),
error: err,
})?;

Ok(inserted_game.id)
Ok(inserted_game.id)
} else {
Ok(-1)
}
}

pub fn fetch_attack_history(
Expand Down

0 comments on commit 65b9e35

Please sign in to comment.