From 19b9a6ea1b8a36ae2301ffbc95cf2f54bf7fa77f Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Tue, 11 Oct 2022 22:58:42 +0200 Subject: add new bot stats endpoint --- planetwars-server/src/routes/bots.rs | 39 ++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'planetwars-server/src/routes') diff --git a/planetwars-server/src/routes/bots.rs b/planetwars-server/src/routes/bots.rs index 4ab1b4e..f8087fd 100644 --- a/planetwars-server/src/routes/bots.rs +++ b/planetwars-server/src/routes/bots.rs @@ -7,6 +7,7 @@ use rand::distributions::Alphanumeric; use rand::Rng; use serde::{Deserialize, Serialize}; use serde_json::{self, json, value::Value as JsonValue}; +use std::collections::HashMap; use std::io::Cursor; use std::path::PathBuf; use std::sync::Arc; @@ -275,3 +276,41 @@ pub async fn get_code( std::fs::read(full_bundle_path).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; Ok(bot_code) } + +#[derive(Default, Serialize, Deserialize)] +pub struct MatchupStats { + win: i64, + loss: i64, + tie: i64, +} + +impl MatchupStats { + fn update(&mut self, win: Option, count: i64) { + match win { + Some(true) => self.win += count, + Some(false) => self.loss += count, + None => self.tie += count, + } + } +} + +type BotStats = HashMap>; + +pub async fn get_bot_stats( + conn: DatabaseConnection, + Path(bot_name): Path, +) -> Result, StatusCode> { + let stats_records = db::matches::fetch_bot_stats(&bot_name, &conn) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let mut bot_stats: BotStats = HashMap::new(); + for record in stats_records { + bot_stats + .entry(record.opponent) + .or_default() + .entry(record.map) + .or_default() + .update(record.win, record.count); + } + + Ok(Json(bot_stats)) +} -- cgit v1.2.3