implement leaderboard endpoint

This commit is contained in:
Ilion Beyst 2022-05-17 21:13:29 +02:00
parent a7d56ba0f5
commit 30de8107b4
3 changed files with 36 additions and 1 deletions

View file

@ -1,7 +1,8 @@
use diesel::{prelude::*, PgConnection, QueryResult}; use diesel::{prelude::*, PgConnection, QueryResult};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::schema::{bots, ratings}; use crate::db::bots::Bot;
use crate::schema::{bots, ratings, users};
#[derive(Queryable, Debug, Insertable, PartialEq, Serialize, Deserialize)] #[derive(Queryable, Debug, Insertable, PartialEq, Serialize, Deserialize)]
pub struct Rating { pub struct Rating {
@ -25,3 +26,29 @@ pub fn set_rating(bot_id: i32, rating: f64, db_conn: &PgConnection) -> QueryResu
.set(ratings::rating.eq(rating)) .set(ratings::rating.eq(rating))
.execute(db_conn) .execute(db_conn)
} }
#[derive(Queryable, Serialize, Deserialize)]
pub struct Author {
id: i32,
username: String,
}
#[derive(Queryable, Serialize, Deserialize)]
pub struct RankedBot {
pub bot: Bot,
pub author: Option<Author>,
pub rating: f64,
}
pub fn get_bot_ranking(db_conn: &PgConnection) -> QueryResult<Vec<RankedBot>> {
bots::table
.left_join(users::table)
.inner_join(ratings::table)
.select((
bots::all_columns,
(users::id, users::username).nullable(),
ratings::rating,
))
.order_by(ratings::rating.desc())
.get_results(db_conn)
}

View file

@ -91,6 +91,7 @@ pub fn api() -> Router {
"/matches/:match_id/log", "/matches/:match_id/log",
get(routes::matches::get_match_log), get(routes::matches::get_match_log),
) )
.route("/leaderboard", get(routes::bots::get_ranking))
.route("/submit_bot", post(routes::demo::submit_bot)) .route("/submit_bot", post(routes::demo::submit_bot))
.route("/save_bot", post(routes::bots::save_bot)) .route("/save_bot", post(routes::bots::save_bot))
} }

View file

@ -12,6 +12,7 @@ use std::path::PathBuf;
use thiserror; use thiserror;
use crate::db::bots::{self, CodeBundle}; use crate::db::bots::{self, CodeBundle};
use crate::db::ratings::{RankedBot, self};
use crate::db::users::User; use crate::db::users::User;
use crate::modules::bots::save_code_bundle; use crate::modules::bots::save_code_bundle;
use crate::{DatabaseConnection, BOTS_DIR}; use crate::{DatabaseConnection, BOTS_DIR};
@ -170,6 +171,12 @@ pub async fn list_bots(conn: DatabaseConnection) -> Result<Json<Vec<Bot>>, Statu
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
} }
pub async fn get_ranking(conn: DatabaseConnection) -> Result<Json<Vec<RankedBot>>, StatusCode> {
ratings::get_bot_ranking(&conn)
.map(Json)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
// TODO: currently this only implements the happy flow // TODO: currently this only implements the happy flow
pub async fn upload_code_multipart( pub async fn upload_code_multipart(
conn: DatabaseConnection, conn: DatabaseConnection,