allow to change name
This commit is contained in:
28
src/game.rs
28
src/game.rs
@@ -3,11 +3,12 @@ use axum::{
|
||||
extract::{Path, State},
|
||||
http::HeaderMap,
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
routing::get,
|
||||
Router,
|
||||
routing::{get, post},
|
||||
Form, Router,
|
||||
};
|
||||
use axum_extra::extract::CookieJar;
|
||||
use maud::{html, Markup, PreEscaped};
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -40,7 +41,7 @@ async fn index(
|
||||
", do you want to be named something different? No worries, change here 👇"
|
||||
}
|
||||
|
||||
form {
|
||||
form action="/name" method="post" {
|
||||
fieldset role="group" {
|
||||
input
|
||||
name="name"
|
||||
@@ -126,8 +127,29 @@ async fn not_found(cookies: CookieJar, headers: HeaderMap) -> Markup {
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct NameForm {
|
||||
name: String,
|
||||
}
|
||||
|
||||
async fn set_name(
|
||||
State(backend): State<Arc<Backend>>,
|
||||
cookies: CookieJar,
|
||||
Form(form): Form<NameForm>,
|
||||
) -> Response {
|
||||
let (cookies, client) = backend.client(cookies).await;
|
||||
|
||||
// Update the client's name in the backend
|
||||
// TODO: handle succ/err msg
|
||||
let _ = backend.set_client_name(&client, &form.name).await;
|
||||
|
||||
// Redirect back to the game page
|
||||
(cookies, Redirect::to("/game")).into_response()
|
||||
}
|
||||
|
||||
pub(super) fn routes() -> Router<Arc<Backend>> {
|
||||
Router::new()
|
||||
.route("/game", get(index))
|
||||
.route("/name", post(set_name))
|
||||
.route("/{*uuid}", get(game))
|
||||
}
|
||||
|
24
src/main.rs
24
src/main.rs
@@ -90,6 +90,30 @@ impl Backend {
|
||||
let lang = language::language(&cookies, headers);
|
||||
(cookies, Req { client, lang })
|
||||
}
|
||||
|
||||
async fn set_client_name(&self, client: &Client, name: &str) -> Result<(), String> {
|
||||
if name.len() > 25 {
|
||||
return Err("Maximum 25 chars are allowed".into());
|
||||
}
|
||||
if name.len() < 3 {
|
||||
return Err("Minimum of 3 chars needed".into());
|
||||
}
|
||||
|
||||
match self {
|
||||
Backend::Sqlite(db) => {
|
||||
sqlx::query!(
|
||||
"UPDATE client SET name = ? WHERE uuid = ?;",
|
||||
name,
|
||||
client.uuid
|
||||
)
|
||||
.execute(db)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
|
Reference in New Issue
Block a user