add error/succ messages

This commit is contained in:
2025-08-03 12:11:02 +02:00
parent e3fd3bdfcc
commit 811d29b9ec
6 changed files with 272 additions and 116 deletions

View File

@@ -1,9 +1,11 @@
use crate::model::client::Client;
use axum::{http::HeaderMap, routing::get, Router};
use axum_extra::extract::{cookie::Cookie, CookieJar};
use axum_messages::MessagesManagerLayer;
use sqlx::{pool::PoolOptions, sqlite::SqliteConnectOptions, SqlitePool};
use std::{fmt::Display, str::FromStr, sync::Arc};
use tower_http::services::ServeDir;
use tower_sessions::{MemoryStore, SessionManagerLayer};
use uuid::Uuid;
#[macro_use]
@@ -68,6 +70,11 @@ struct Req {
lang: Language,
}
pub(crate) enum NameUpdateError {
TooLong(usize, usize),
TooShort(usize, usize),
}
impl Backend {
async fn client(&self, cookies: CookieJar) -> (CookieJar, Client) {
let existing_uuid = cookies
@@ -91,12 +98,12 @@ impl Backend {
(cookies, Req { client, lang })
}
async fn set_client_name(&self, client: &Client, name: &str) -> Result<(), String> {
async fn set_client_name(&self, client: &Client, name: &str) -> Result<(), NameUpdateError> {
if name.len() > 25 {
return Err("Maximum 25 chars are allowed".into());
return Err(NameUpdateError::TooLong(25, name.len()));
}
if name.len() < 3 {
return Err("Minimum of 3 chars needed".into());
return Err(NameUpdateError::TooShort(3, name.len()));
}
match self {
@@ -118,6 +125,9 @@ impl Backend {
#[tokio::main]
async fn main() {
let session_store = MemoryStore::default();
let session_layer = SessionManagerLayer::new(session_store).with_secure(false);
let connection_options = SqliteConnectOptions::from_str("sqlite://db.sqlite").unwrap();
let db: SqlitePool = PoolOptions::new()
.connect_with(connection_options)
@@ -128,7 +138,9 @@ async fn main() {
.route("/", get(index::index))
.nest_service("/static", ServeDir::new("./static/serve"))
.merge(game::routes())
.with_state(Arc::new(Backend::Sqlite(db)));
.with_state(Arc::new(Backend::Sqlite(db)))
.layer(MessagesManagerLayer)
.layer(session_layer);
// run our app with hyper, listening globally on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();