shared state works

This commit is contained in:
clizia 2025-03-03 21:38:11 +01:00
parent 4ede781f50
commit ed3c9694c0
3 changed files with 34 additions and 22 deletions

View file

@ -9,13 +9,7 @@ use crossterm::{
},
event::Event,
};
use http_body_util::Empty;
use hyper::{client::conn::{self, http1::{self, handshake}}, Request};
use hyper::body::Bytes;
use hyper_util::rt::TokioIo;
use tokio::net::TcpStream;
#[allow(unreachable_code)]
#[tokio::main]
pub async fn main() -> anyhow::Result<()> {
// let mut client = Client::connect("127.0.0.1", 8080).await?;
@ -31,9 +25,13 @@ pub async fn main() -> anyhow::Result<()> {
let client = reqwest::Client::new();
let player = Player::new()?;
let message = Message::new(&player.get_name(), MessageKind::Test, player.encode()?)?;
let response = client
.post([&addr, "/create/player"].concat())
.body(Player::new()?.encode()?)
.header("Content-Type", "application/json")
.body(message.encode()?)
.send().await?
.text().await?;

View file

@ -2,6 +2,8 @@ use petname::Generator;
use serde::{Deserialize, Serialize};
use sha256::digest;
use axum::Json;
use crate::card::Card;
#[derive(Serialize, Deserialize, Eq, PartialEq, Hash, Clone)]
@ -28,7 +30,7 @@ impl Player {
}
pub fn encode(&self) -> anyhow::Result<String> {
let player_json: String = serde_json::to_string(self)?;
let player_json = serde_json::to_string(self)?;
Ok(player_json)
}
@ -39,11 +41,11 @@ impl Player {
Ok(player)
}
pub fn get_name(self) -> String {
self.name
pub fn get_name(&self) -> String {
self.name.clone()
}
pub fn get_hand(self) -> Vec<Card> {
self.hand
pub fn get_hand(&self) -> Vec<Card> {
self.hand.clone()
}
}

View file

@ -1,15 +1,14 @@
use anyhow::Result;
use axum::{
Router,
body::Bytes,
extract::{
State,
Json,
rejection::JsonRejection,
},
body::Bytes, extract::{
rejection::JsonRejection, Json, State
}, response::ErrorResponse, Router
};
use hyper::StatusCode;
use crate::message::Message;
use crate::{message::Message, player::Player};
use crate::db::AppState;
use crate::message::MessageKind;
pub struct App {
pub db: AppState,
@ -34,13 +33,26 @@ impl App {
pub async fn create_player(
State(db): State<AppState>,
json_body: Result<Json<Message>, JsonRejection>,
)
) -> Result<axum::Json<Message>, StatusCode>
{
match json_body {
Ok(Json(message)) => {
println!("{:?}", message);
let player: Player = serde_json::from_str(&message.content).expect("niente json");
{
let mut players = db.players
.lock().expect("ciao");
players.insert(
player.get_name(),
Bytes::copy_from_slice(player.encode().expect("failed encoding player").as_ref())
);
}
println!("{:?}", db.players);
Ok(Json(Message::new("server", MessageKind::CreatePlayer, "user created").expect("failed creating message")))
}
Err(e) => eprintln!("{e}"),
Err(_) => Err(StatusCode::UNPROCESSABLE_ENTITY)
}
}
}