diff options
author | Ilion Beyst <ilion.beyst@gmail.com> | 2022-03-06 16:53:02 +0100 |
---|---|---|
committer | Ilion Beyst <ilion.beyst@gmail.com> | 2022-03-06 16:53:02 +0100 |
commit | 148178a344dd42ccf00356cad06f4e635e78bda7 (patch) | |
tree | 48e6516a4ec04f093ee5cdcea83db7e63fabd6dc /planetwars-server | |
parent | bd5dd17eb91f6501fb1944040e9d547c148a60aa (diff) | |
download | planetwars.dev-148178a344dd42ccf00356cad06f4e635e78bda7.tar.xz planetwars.dev-148178a344dd42ccf00356cad06f4e635e78bda7.zip |
return descriptive errors when saving bots
Diffstat (limited to 'planetwars-server')
-rw-r--r-- | planetwars-server/src/routes/bots.rs | 30 |
1 files changed, 27 insertions, 3 deletions
diff --git a/planetwars-server/src/routes/bots.rs b/planetwars-server/src/routes/bots.rs index 6a5612a..c9bf8ce 100644 --- a/planetwars-server/src/routes/bots.rs +++ b/planetwars-server/src/routes/bots.rs @@ -1,11 +1,13 @@ +use axum::body; use axum::extract::{Multipart, Path}; use axum::http::StatusCode; +use axum::response::{IntoResponse, Response}; use axum::Json; use diesel::OptionalExtension; use rand::distributions::Alphanumeric; use rand::Rng; use serde::{Deserialize, Serialize}; -use serde_json::{json, value::Value as JsonValue}; +use serde_json::{self, json, value::Value as JsonValue}; use std::io::Cursor; use std::path::PathBuf; @@ -20,16 +22,38 @@ pub struct SaveBotParams { pub bot_name: String, pub code: String, } + +pub enum SaveBotError { + BotNameTaken, +} + +impl IntoResponse for SaveBotError { + fn into_response(self) -> Response { + let (status, value) = match self { + SaveBotError::BotNameTaken => { + (StatusCode::FORBIDDEN, json!({ "error": "BotNameTaken" })) + } + }; + + let encoded = serde_json::to_vec(&value).expect("could not encode response value"); + + Response::builder() + .status(status) + .body(body::boxed(body::Full::from(encoded))) + .expect("could not build response") + } +} + pub async fn save_bot( Json(params): Json<SaveBotParams>, conn: DatabaseConnection, -) -> Result<Json<Bot>, StatusCode> { +) -> Result<Json<Bot>, SaveBotError> { // TODO: authorization let res = bots::find_bot_by_name(¶ms.bot_name, &conn) .optional() .expect("could not run query"); let bot = match res { - Some(_bot) => return Err(StatusCode::FORBIDDEN), + Some(_bot) => return Err(SaveBotError::BotNameTaken), None => { let new_bot = bots::NewBot { owner_id: None, |