cards/server/src/api/message_handler.rs

64 lines
2.1 KiB
Rust
Raw Normal View History

2024-07-16 21:11:24 -04:00
use crate::api::{greeting, Message, User};
2024-05-04 02:23:40 -04:00
use crate::AppState;
use crate::Arc;
2024-07-21 23:28:06 -04:00
use anyhow::Result;
2024-07-21 02:35:13 -04:00
use lib::models::*;
2024-06-22 02:16:35 -04:00
2024-07-16 21:11:24 -04:00
pub async fn message_handler(message: Message, state: &Arc<AppState>, who: &User) {
2024-05-04 02:23:40 -04:00
let tx = &state.tx;
match message {
Message::Text(text) => {
if let Ok(new_game) = serde_json::from_str::<NewGameRequest>(&text) {
2024-07-21 22:48:15 -04:00
tracing::debug!("New game request received.");
2024-05-04 02:23:40 -04:00
// create game
2024-07-21 22:48:15 -04:00
if let Ok(new_game_object) = Game::new(new_game) {
2024-07-21 23:28:06 -04:00
if let Ok(game_json) = serde_json::to_string(&new_game_object) {
tracing::debug!("Sent new game JSON.");
let _ = tx.send(game_json);
} else {
tracing::error!("Failed to convert Game object to JSON.")
}
2024-05-04 02:23:40 -04:00
state.games.lock().unwrap().push(new_game_object);
2024-07-21 00:59:21 -04:00
let _update = tx.send(greeting(state));
2024-05-04 02:23:40 -04:00
} else {
2024-07-21 00:59:21 -04:00
let _res = tx.send(String::from("error creating game"));
2024-05-04 02:23:40 -04:00
}
} else {
// just echo
2024-07-16 21:11:24 -04:00
let msg = format! {"{0}: {1}", who.name, text};
2024-05-04 02:23:40 -04:00
tracing::debug!("{msg}");
let _res = tx.send(msg);
}
}
Message::Binary(data) => {
tracing::debug!("Binary: {:?}", data)
}
Message::Close(c) => {
if let Some(cf) = c {
tracing::debug!(
2024-07-16 21:11:24 -04:00
"Close received from {0} with code: {1} and reason: {2}",
who.addr,
2024-05-04 02:23:40 -04:00
cf.code,
cf.reason
)
} else {
tracing::debug!("close received without close frame")
}
2024-07-16 21:11:24 -04:00
let msg = format!("{0} left.", who.name);
2024-05-04 02:23:40 -04:00
tracing::debug!("{msg}");
let _ = tx.send(msg);
}
Message::Pong(ping) => {
tracing::debug!("Pong received with: {:?}", ping);
}
Message::Ping(pong) => {
tracing::debug!("Pong received with: {:?}", pong);
}
}
}