ddguesser/src/app/mod.rs

69 lines
2.0 KiB
Rust

use rocket::{response::Redirect, Route, State};
use rocket_dyn_templates::{context, Template};
use uuid::Uuid;
use crate::database::{
models::{
guess::Guess,
location::{self, Location},
},
DatabaseHandler,
};
#[get("/")]
fn landing() -> Template {
Template::render("landing", context! {})
}
#[get("/start-game")]
async fn start_game(db: &State<DatabaseHandler>) -> Result<Redirect, String> {
Location::get_random(db, true)
.await
.map(|location| Redirect::to(format!("/location/{}", location.id)))
.map_err(|_| {
"Sorry for this, but the game ran into an error. Please try again!".to_string()
})
}
#[get("/location/<id>")]
async fn location_via_id(db: &State<DatabaseHandler>, id: String) -> Result<Template, String> {
let uuid = match Uuid::parse_str(&id) {
Ok(uuid) => uuid,
Err(_) => return Err("Sorry, that id seems invalid!".to_string()),
};
let location = match Location::get_by_id(db, &uuid).await {
Ok(location) => location,
Err(_) => return Err("Sorry, that location seems invalid!".to_string()),
};
Ok(Template::render("location", context! { location }))
}
#[get("/location/<id>?<guess>")]
async fn location_guess_via_id(
db: &State<DatabaseHandler>,
id: String,
guess: String,
) -> Result<Template, String> {
let uuid = match Uuid::parse_str(&id) {
Ok(uuid) => uuid,
Err(_) => return Err("Sorry, that id seems invalid!".to_string()),
};
let location = match Location::get_by_id(db, &uuid).await {
Ok(location) => location,
Err(_) => return Err("Sorry, that location seems invalid!".to_string()),
};
let is_guess_correct = guess == location.map;
let guess_with_results = Guess::create(guess, is_guess_correct);
Ok(Template::render(
"location",
context! { location, guess: guess_with_results },
))
}
pub fn get_all_routes() -> Vec<Route> {
routes![landing, start_game, location_via_id, location_guess_via_id]
}